package swing;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
* 点击面板上的按钮,改变相应的颜色
*
* 1.都是用字符串构造button
* 2.都是将该button添加到panel
* 3.都是用对应的颜色构造一个监听器
* 4.都会添加监听器动作
*/
public class ButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ButtonFrame extends JFrame {
public ButtonFrame() {
this.setTitle("Button Test");
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
buttonPanel = new JPanel();
this.makeButton("Yellow", Color.YELLOW);
this.makeButton("Blue", Color.BLUE);
this.makeButton("Red", Color.RED);
//将panel添加至frame
this.add(buttonPanel);
}
private void makeButton(String name, final Color backgroundColor) {
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
buttonPanel.setBackground(backgroundColor);
}
});
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private JPanel buttonPanel;
}