Parag
Parag

Reputation: 12453

Pros and cons of using ActionListener vs. MouseListener for capturing clicks on a JButton

I have a JButton, and would like to capture mouse clicks on it. What are the practical and philosophical differences between using an ActionListener vs. using a MouseListener on the JButton ?

Upvotes: 11

Views: 8074

Answers (3)

EdC
EdC

Reputation: 2349

Fundamentally, MouseListener is for picking up arbitary clicks. ActionListener is for picking up "someone actioning the button". So if you're really interested in the buton being activated use ActionListener. That way you'll get the event if it's activated via the keyboard or any other mechanism.

MouseListener on the other hand should be used if you're interested specifically in the click. E.g. which part of the button did they click on, did they click on something that's not activatable etc.

Upvotes: 3

Alex
Alex

Reputation: 25613

If you just want to know that the button has been pressed use ActionListener. If your checks involve deeper analysis like mouse state (mouse entered the button, exited) etc, use MouseListener

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691765

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: 16

Related Questions