tags:

views:

39

answers:

3

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");
    }
});
+1  A: 

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.

vladmihaisima
A: 

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.

Andreas_D
+2  A: 

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 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 the action (amd it s associated widgets) is enabled or not.

jfpoilpret