package java01;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
/**
* 我的java每天100行代码003
* 利用按钮实现更换背景的效果
* @author Administrator
*
*/
public class java003{
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}
class ButtonFrame extends JFrame{
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ButtonFrame() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
JButton yellowButton = new JButton("yellow");
JButton blueButton = new JButton("blue");
JButton redButton = new JButton("red");
buttonPanel = new JPanel();
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
add(buttonPanel);
ActionListener yellowAction = new ColorAction(Color.YELLOW);
ActionListener blueAction = new ColorAction(Color.BLUE);
ActionListener redAction = new ColorAction(Color.RED);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
//静态内部类
private class ColorAction implements ActionListener{
private Color backgroundColor;
public ColorAction(Color c){
backgroundColor = c;
}
public void actionPerformed(ActionEvent e) {
buttonPanel.setBackground(backgroundColor);
}
}
}
Java 100-003:利用按钮实现更换背景的效果
最新推荐文章于 2021-03-02 02:25:24 发布