2.4.事件监听
事件监听:当某个事情发生的时候,干什么?
package com.gui.lesson01;
import com.zzx.oop.abc.B;
import javax.swing.*;
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
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
//
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setSize(400,400);
frame.setVisible(true);
windowClose(frame);
}
//关闭窗口事件
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");
}
}
多个按钮共享一个事件
package com.gui.lesson01;
import java.awt.*;
import java.awt.event.*;
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);
WindowListener windowListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(windowListener);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了:msg"+e.getActionCommand());
if (e.getActionCommand().equals("start")){
}
}
}