这样写
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Demo8_8 extends JFrame implements ActionListener {
JPanel mp = null;
JButton jb1 = null;
JButton jb2 = null;
public static void main(String[] args) {
Demo8_8 demo8_8 = new Demo8_8();
}
public Demo8_8() {
mp = new JPanel();
jb1 = new JButton("balck");
jb2 = new JButton("red");
this.add(jb1, BorderLayout.NORTH);
mp.setBackground(Color.black);
this.add(mp);
this.add(jb2, BorderLayout.SOUTH);
// 注册监听
jb1.addActionListener(this);
jb1.setActionCommand("black");
jb2.addActionListener(this);
jb1.setActionCommand("red");
this.setSize(200, 150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
// 对事件处理的方法
public void actionPerformed(ActionEvent e) {
// 判断那个按钮被点击
if (e.getActionCommand().equals("black"))
System.out.println("你点击了黑色按钮");
else
System.out.println("你点击了红色按钮");
}
}
需要导入类
import java.awt.event.ActionEvent;
修改这个东西
jb2.addActionListener(this);
jb2.setActionCommand("red");