鼠标侦听器和动作侦听器之间的区别?

Difference between Mouse Listener and Action Listener?

有什么区别?你什么时候会使用鼠标侦听器?还是动作监听器? 谢谢,麻烦您了!

ActionListener 文档

The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.

MouseListener 文档

The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.)

从文档中可以看出,这个接口的用法是完全不同的。虽然 MouseListener 只能与 gui 元素结合使用,但 ActionListener 也可以在没有 gui 的情况下使用,例如与计时器结合使用。

第一个区别是 MouseEvent 是真正的系统事件,而 ActionEvent 是合成事件...它由系统事件触发。

MouseListener(和 MouseMotionLister、MouseWheelListener)在 (a) 您对事件详细信息(即 x/y 点击点)感兴趣或当您使用的组件不支持 ActionListeners 时很有用

Action 当您有一项可以在没有外部事件详细信息(例如退出程序)的情况下执行的任务并且您希望能够在多个组件中访问,或者使用键盘或鼠标启动/启动

ActionListener 用于处理按钮的逻辑点击。发生点击:

  • 当鼠标在按钮上按下然后松开时,
  • 或者当使用该按钮的快捷键时,
  • 或者当按钮获得焦点并按下 space 栏时,
  • 或者当按钮为默认按钮并按下 Enter 时,
  • 或者以编程方式调用按钮的 click() 方法时

MouseListener 仅处理低级鼠标事件。