AddMouseListener or addActionListener or JButton?

Determining the behavior of a simple click on JButton, is this the right way to do this? And what's the difference?

JButton but = new JButton(); but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("You clicked the button, using an ActionListener"); } }); 

or

 JButton but = new JButton(); but.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { System.out.println("You clicked the button, using a MouseListenr"); } }); 
+6
java button swing
source share
4 answers

MouseListener is a low-level event listener in Swing (and AWT by the way).

ActionListener is a higher level and should be used.

Better than ActionListener , although you should use javax.swing.Action (which is actually an ActionListener ).

Using Action allows you to split it between multiple widgets (for example, JButton , JMenuItem ...); you not only use the code that starts when you press the button / menu, but also the sharing status, in particular, the fact of the inclusion or absence of an action (and related widgets).

+6
source share

You can also press this button using the keyboard. So, if you add only the mouse listener, you will not get a β€œclick” event if you use the keyboard.

I would go for an action listener, it was more clear.

+1
source share

The registered ActionListener is called when the button fires the Action event, the MouseListener is called when the widget detects a mouse click.

In your example, both approaches show the same behavior when you use the mouse to click on a button. But focus on the button and press SPACE , this should trigger an event event and call an action listener, but not a mouse listener.

It is advisable to use the ActionListener on the buttons, otherwise you will not be able to control the application using the keyboard, otherwise you will need to add another event listener.

0
source share

If you want to do something when Jbutton is clicked, the action listener is better because the mouse listener does not recognize that the mouse is pressed on the button if the user clicks on the JButton and then moves the mouse a bit before releasing the mouse button, staying within buttons all the time but action listener. MouseListener requires mouse clicks not to move between mouse clicks and mouse output, which is not suitable for my users.

-2
source share

All Articles