#头条创作挑战赛#
❝
❤️作者简介:大家好,我是小虚竹。Java领域优质创作者,CSDN博客专家,华为云享专家,掘金年度人气作者,阿里云专家博主,51CTO专家博主
❤️技术活,该赏
❤️点赞 收藏 ⭐再看,养成习惯
❞
零、前言
今天是学习 「JAVA语言」 打卡的第37天,我的学习策略很简单,题海策略+ 费曼学习法。如果能把这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;
}
@Override
public void actionPerformed(ActionEvent e) {
contentPane.setBackground(background);
}
}
}
多学一个知识点
定义在类的是全局变量contentPane,在内部类中是可以直接使用的
我是虚竹哥,我们下一题见~