一个按钮监听一个事件

例子:

  • 按下一次按钮就会打印指定的文字。 ```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”);

  1. MyActionListener myActionListener = new MyActionListener();
  2. button.addActionListener(myActionListener);
  3. frame.add(button, BorderLayout.CENTER);//加入按钮,按钮居中
  4. frame.pack();//自适应
  5. windowClose(frame);//点× 关闭窗口
  6. frame.setVisible(true);
  7. }
  8. //关闭窗口事件
  9. private static void windowClose(Frame frame) {
  10. frame.addWindowListener(new WindowAdapter() {
  11. @Override
  12. public void windowClosing(WindowEvent e) {
  13. System.exit(0);
  14. }
  15. });
  16. }

}

//事件监听 class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println(“WTY2002”); } }

  1. ![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)
  2. <a name="ofsyr"></a>
  3. # 多个按钮监听一个事件
  4. ```java
  5. package gui;
  6. import java.awt.*;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. public class TestActionTwo {
  10. public static void main(String[] args) {
  11. //两个按钮,实现同一个监听
  12. //开始 停止
  13. Frame frame = new Frame("开始-停止");
  14. Button button1 = new Button("start");
  15. Button button2 = new Button("stop");
  16. //可以显示的定义触发会返回的命令, 如果不显示定义,则会走默认值
  17. //可以多个按钮只写一个监听类
  18. button2.setActionCommand("button2-stop");
  19. MyMonitor myMonitor = new MyMonitor();
  20. button1.addActionListener(myMonitor);
  21. button2.addActionListener(myMonitor);
  22. frame.add(button1,BorderLayout.NORTH);
  23. frame.add(button2,BorderLayout.SOUTH);
  24. frame.pack();
  25. frame.setVisible(true);
  26. }
  27. }
  28. class MyMonitor implements ActionListener{
  29. @Override
  30. public void actionPerformed(ActionEvent e) {
  31. //e.getActionCommand() 获得按钮的信息
  32. System.out.println("按钮被点击了:msg: " + e.getActionCommand());
  33. }
  34. }

image.pngimage.png