11

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 ?

Parag
  • 12,093
  • 16
  • 57
  • 75
  • 2
    for questions like this, be sure to read the relevant chapter in the online tutorial referenced in the swing tag wiki, here for starters [General Information about Writing Event Listeners](http://docs.oracle.com/javase/tutorial/uiswing/events/generalrules.html) – kleopatra Nov 23 '12 at 10:36
  • 2
    A vs. B? I suggest C) An `Action`. See [How to Use Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) for details. – Andrew Thompson Nov 23 '12 at 11:42

3 Answers3

16

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

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

Alex
  • 25,147
  • 6
  • 59
  • 55
3

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.

EdC
  • 2,309
  • 1
  • 17
  • 30