Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 455
Parag Avatar asked Nov 23 '12 09:11

Parag


People also ask

What is the difference between ActionListener and MouseLIstener?

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.

Can I implement both ActionListener and MouseLIstener?

You should not be using a MouseLIstener to handle mouse clicks on a button. You should just be using an ActionListener. Then the same ActionListener can be added to the button and the text field.


2 Answers

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.

like image 194
JB Nizet Avatar answered Oct 23 '22 21:10

JB Nizet


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

like image 31
Alex Avatar answered Oct 23 '22 20:10

Alex