Marcella Ruiz
Marcella Ruiz

Reputation: 323

Difference between Mouse Listener and Action Listener?

Whats the difference? When would you use a mouse listener? or a action listener? Please and Thank You!

Upvotes: 6

Views: 10629

Answers (3)

Mayuri
Mayuri

Reputation: 489

An ActionListener is used to handle the logical click of a button. A click happens:

  • when the mouse is pressed then released on a button,
  • or when the keyboard shortcut of that button is used,
  • or when the button has the focus and the space bar is pressed,
  • or when the button is the default button and Enter is pressed,
  • or when the button's click() method is called programmatically

A MouseListener only handles low-level mouse events.

Upvotes: 3

ControlAltDel
ControlAltDel

Reputation: 35011

The first difference is that A MouseEvent is a true system event, whereas an ActionEvent is a synthesized event... It is triggered by a system event.

MouseListener (and MouseMotionLister, MouseWheelListener) are useful when (a) you are interested in the event details (ie x/y click spot) or when the component you are using doesn't support ActionListeners

Actions are good when you have a task that can executed without external event details (like exiting the program) and that you'd like to be able to access either in more than one component, or to set off / start with either the keyboard or the mouse

Upvotes: 5

kai
kai

Reputation: 6887

ActionListener Doc's

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 Doc's

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.)

From the docs you can see that the usage of this interfaces is completly different. While you can use the MouseListener only in combination with gui elements, the ActionListener is also used when there is no gui, for example in combination with a timer.

Upvotes: 3

Related Questions