文章目录
零、前言
今天是学习 JAVA语言 打卡的第37天,每天我会提供一篇文章供群成员阅读( 不需要订阅付钱 ),读完文章之后,按解题思路,自己再实现一遍。在小虚竹JAVA社区 中对应的 【打卡贴】打卡,今天的任务就算完成了。
因为大家都在一起学习同一篇文章,所以有什么问题都可以在群里问,群里的小伙伴可以迅速地帮到你,一个人可以走得很快,一群人可以走得很远,有一起学习交流的战友,是多么幸运的事情。
学完后,自己写篇学习报告的博客,可以发布到小虚竹JAVA社区 ,供学弟学妹们参考。
我的学习策略很简单,题海策略+ 费曼学习法。如果能把这100题都认认真真自己实现一遍,那意味着 JAVA语言 已经筑基成功了。后面的进阶学习,可以继续跟着我,一起走向架构师之路。
一、题目描述
题目:在类中,除以可以定义参数,方法和块,还可以定义类。这种类叫做内部类。
实现:在界面中定义3个按钮,用户通过单击不同的按钮,可以给面板设置不同的颜色。
二、解题思路
写一个按钮类ButtonTest,这个类继承JFrame
在窗体中添加3个按钮,红色按钮,绿色按钮和蓝色按钮
编写内部类-按钮事件类:ColorAction,继承ActionListener接口。
三、代码详解
按钮类:
public class ButtonTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = -5726190585100402900L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ButtonTest frame = new ButtonTest();
frame.setVisible(true);
frame.contentPane.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ButtonTest() {
setTitle("普通内部类的简单应用");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 200);
contentPane = new JPanel();
contentPane.setLayout(null);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
final JButton redButton = new JButton();
redButton.setText("红色");
redButton.setBounds(15, 20, 82, 30);
redButton.addActionListener(new ColorAction(Color.RED));
contentPane.add(redButton);
final JButton greenButton = new JButton();
greenButton.setText("绿色");
greenButton.setBounds(100, 20, 82, 30);
greenButton.addActionListener(new ColorAction(Color.GREEN));
contentPane.add(greenButton);
final JButton blueButton = new JButton();
blueButton.setText("蓝色");
blueButton.setBounds(185, 20, 82, 30);
blueButton.addActionListener(new ColorAction(Color.BLUE));
contentPane.add(blueButton);
}
private class ColorAction implements ActionListener {
private Color background;
public ColorAction(Color background) {
this.background = background;
}
public void actionPerformed(ActionEvent e) {
contentPane.setBackground(background);
}
}
}
多学一个知识点
定义在类的是全局变量contentPane,在内部类中是可以直接使用的