button的监听
package hike.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 TestAction {
public static void main(String[] args) {
// 按下按钮,触发一些事件
Frame frame = new Frame();
Button button = new Button("测试事件");
button.setSize(80,30);
// 因为 addActionListener() 需要一个 ActionListener,所有我们需要构造一个 ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button, BorderLayout.CENTER);
frame.setBounds(100,200,400,400);
frame.pack(); // 容器自适应
windowClose(frame);
frame.setVisible(true);
}
// 关闭窗体的事件 抽离成一个方法
private static void windowClose(Frame frame) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
// 动作监听
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}