package ch10;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class ColorChange extends JFrame{
JPanel p;
JButton btnRed,btnGreen,btnYellow;
public ColorChange() {
super("动作事件测试");
p = new JPanel();
btnRed = new JButton("变红");
btnGreen = new JButton("变绿");
btnYellow = new JButton("变黄");
p.add(btnRed);
p.add(btnGreen);
p.add(btnYellow);
//创建一个监听对象
ButtonListener b1 = new ButtonListener();
//给按钮注册监听对象
btnRed.addActionListener(b1);
btnGreen.addActionListener(b1);
btnYellow.addActionListener(b1);
this.add(p);
this.setSize(300,200);
this.setLocation(100,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//创建扩展ActionListener的监听类
public class ButtonListener implements ActionListener{
//重写ActionListener接口中的事件处理方法actionPerformed()
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();//获取事件源
//判断事件源,进行相应处理
if(source==btnRed) {
p.setBackground(Color.red);
}else if(source==btnGreen) {
p.setBackground(Color.green);
}else {
p.setBackground(Color.yellow);
}
}
}
public static void main(String[] args) {
ColorChange cf = new ColorChange();
cf.setVisible(true);
}
}
java通过创建监听类,实现单击按钮改变面板的背景颜色
最新推荐文章于 2022-01-14 20:35:24 发布