package ch10;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class ColorChange2 extends JFrame{
JPanel p;
JButton btnRed,btnGreen,btnYellow;
public ColorChange2() {
super("动作事件测试2");
p = new JPanel();
btnRed = new JButton("变红");
btnGreen = new JButton("变绿");
btnYellow = new JButton("变黄");
p.add(btnRed);
p.add(btnGreen);
p.add(btnYellow);
//使用匿名监听类的方式注册监听对象
btnRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.red);
}
});
btnGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.green);
}
});
btnYellow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.yellow);
}
});
this.add(p);
this.setSize(300,200);
this.setLocation(100,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
ColorChange2 cf = new ColorChange2();
cf.setVisible(true);
}
}
java通过创建匿名监听类的方法实现单击按钮改变面板的背景颜色
最新推荐文章于 2023-03-27 13:26:15 发布