When defining the behaviour of a simple click on a JButton, which is the right way to do it? And, what\'s the difference?
JButton but = new JButton();
but.ad
You should be able to press that button using keyboard also. So, if you add just the mouse listener you will not get the 'press' event if using keyboard.
I would go for the action listener, it's more clear.
If you want to do something when a Jbutton is clicked, action listener is better because mouse listener does not recognize that a mouse is clicked on a button if a user presses the mouse on a JButton and then moves the mouse a little bit before releasing the mouse button while remaining within the button the whole time, but action listener does. MouseListener requires that mouse clicks have no movement between mouse press and mouse release, which is not the case for my users.
MouseListener
is a low-level event listener in Swing (and AWT by the way).
ActionListener
is higher-level and should be used.
Better than ActionListener
though, one should use a javax.swing.Action
(which is actually an ActionListener
).
Using an Action
allows to share it among several widgets (eg JButton
, JMenuItem
...); not only do you share the code that is triggered when the button/menu is pushed, but also the state is shared, in particular the fact whether the action (and its associated widgets) is enabled or not.
A registered ActionListener
is invoked when the Button fires an Action event, the MouseListener
is invoked when the widget detects a mouse click.
In your example both approaches show the same behaviour when you use a mouse to click on the button. But give focus to the button and press SPACE
, this should fire an action event and trigger the Action Listener but not the mouse listener.
It is advisable to use the ActionListener on Buttons, otherwise you'll not be able to control the application with a keyboard or you would be in the need to add another key event listener.