ActionListener 实现背景颜色的改变
/**
*
* @class ChangerColor
* @param 按钮监听来改变背景颜色
*/
public class ChangerColor extends JFrame {
JPanel p;
JButton btYellow,btRed,btGreen;
public ChangerColor () {
super("事件测试-改变颜色");
p =new JPanel();
btGreen=new JButton("绿色");
btRed = new JButton("红色");
btYellow=new JButton("黄色");
//创建一个监听对象
ButtonListener btListener = new ButtonListener();
//注册监听
btGreen.addActionListener(btListener);
btRed.addActionListener(btListener);
btYellow.addActionListener(btListener);
p.add(btGreen);
p.add(btRed);
p.add(btYellow);
this.add(p);
this.setSize(300,300);
this.setLocation(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class ButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source==btGreen) {
p.setBackground(Color.GREEN);
}
else if (source==btRed){
p.setBackground(Color.RED);
}else {
p.setBackground(Color.YELLOW);
}
}
}
public static void main(String[] args) {
new ChangerColor();
}