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");
}
});
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With