/*
* 功能:java事件监听器ActionListener
*/
package com.events;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class changebgcolor extends JFrame implements ActionListener{
JButton jb1,jb2;
JPanel jpn;
public static void main(String[] args){
changebgcolor cbgcolor=new changebgcolor();
}
public changebgcolor(){
jb1=new JButton("红色背景");
jb2=new JButton("蓝色背景");
jpn=new JPanel();
jpn.setBackground(Color.yellow);
//添加按钮1
this.add(jb1,BorderLayout.NORTH);
//添加按钮2
this.add(jb2,BorderLayout.SOUTH);
//添加面板
this.add(jpn);
//设置监听命令
jb1.setActionCommand("背景变红色");
//设置监听对象
jb1.addActionListener(this);
jb2.setActionCommand("背景变蓝色");
jb2.addActionListener(this);
this.setTitle("事件监听功能:实现改变窗体背景颜色");
this.setSize(200,150);
this.setLocation(200, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
//对事件的处理方法
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("背景变红色")){
jpn.setBackground(Color.red);
}
if(e.getActionCommand().equals("背景变蓝色")){
jpn.setBackground(Color.blue);
}
}
}
转载于:https://blog.51cto.com/6846041/1332166