一个按钮监听一个事件
例子:
- 按下一次按钮就会打印指定的文字。 ```java package gui;
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(“btn”);
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button, BorderLayout.CENTER);//加入按钮,按钮居中
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(“WTY2002”); } }
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1640355036883-885a2ece-b963-4077-9d54-1ce0f3645134.png#clientId=u72700357-b1a6-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=154&id=u4a9b369f&margin=%5Bobject%20Object%5D&name=image.png&originHeight=49&originWidth=122&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1857&status=done&style=none&taskId=u5fba8668-9179-41b5-bc15-1c883bb82d1&title=&width=383)![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1640355060148-f4c66b0c-0611-4b36-89da-c0cb943e13ab.png#clientId=u72700357-b1a6-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=105&id=u5d70298b&margin=%5Bobject%20Object%5D&name=image.png&originHeight=122&originWidth=442&originalType=binary&ratio=1&rotation=0&showTitle=false&size=9900&status=done&style=none&taskId=ubdd02abf-d73e-43fc-a63b-727452ed0bb&title=&width=381)
<a name="ofsyr"></a>
# 多个按钮监听一个事件
```java
package gui;
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.getActionCommand() 获得按钮的信息
System.out.println("按钮被点击了:msg: " + e.getActionCommand());
}
}