Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addMouseListener or addActionListener or JButton?

Tags:

java

button

swing

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.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");
    }
});
like image 941
Hectoret Avatar asked Sep 01 '10 09:09

Hectoret


2 Answers

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.

like image 119
jfpoilpret Avatar answered Nov 03 '22 01:11

jfpoilpret


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.

like image 30
vladmihaisima Avatar answered Nov 03 '22 01:11

vladmihaisima