[java]代码库
/**
* 功能:按钮事件监听
*/
package com.test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test2 extends JFrame implements ActionListener{
JPanel jP=null;
JButton jb1=null;
JButton jb2=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Test2 test2=new Test2();
}
public Test2(){
jP=new JPanel();
jb1=new JButton("黑色");
jb2=new JButton("红色");
this.add(jb1,BorderLayout.NORTH);
this.add(jb2,BorderLayout.SOUTH);
jP.setBackground(Color.black);
this.add(jP);
//注册监听
jb1.addActionListener(this);
jb2.addActionListener(this);
//指定action命令
jb1.setActionCommand("黑色");
jb2.setActionCommand("红色");
this.setSize(300, 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("黑色")){
jP.setBackground(Color.black);
}else if(e.getActionCommand().equals("红色")){
jP.setBackground(Color.red);
}
}
}