package com.sheng.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame = new Frame();
Button button = new Button();
//因为,addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListner myActionListner = new MyActionListner();
button.addActionListener(myActionListner);
frame.add(button,BorderLayout.CENTER);
frame.pack();
windowClose(frame);//关闭窗口
frame.setVisible(true);
}
//关闭窗体的事件
private static void windowClose(Frame a){
a.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
}
//事件监听
class MyActionListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
多个按钮,共享一个事件
package com.sheng.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestActionTwo {
public static void main(String[] args) {
//两个按钮,实现同一个监听
//开始 停止
Frame frame = new Frame("开始-停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值!
//可以多个按钮只写一个监听类
button2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// e.getActionCom
System.out.println("按钮被点击了:msg=>"+e.getActionCommand());
}
}