#頭條創作挑戰賽#
❝
❤️作者簡介:大家好,我是小虛竹。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,在内部類中是可以直接使用的
我是虛竹哥,我們下一題見~