i am trying to learn more about event handling but everywhere i read about it, it's mainly about how to use it so something happens but not how it works.
So far i know about 2 ways to make something happen when a button is clicked.
ActionListener:
myButton.addActionListener(new ActionListener() { @override actionPerformed... });
and AbstractAction:
public class MyAction extends AbstractAction {
public MyAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Action", e);
}
}
MyAction myAction = new MyAction(...);
myButton.setAction(myAction);
I know that i can write everything i want to happen into the actionPerfomed() method.
But since i do not know, what exactly happens in the background I can not tell if one has any advantage over the other or which one i should use in which situation?
if you extend AbstractAction, you can't extend any other classes. In any case, you might want to avoid subclasses whenever you can. I would personally recommend implementing the interface
ActionListenerand then adding an action Listener to your swing object (or whatever you listen on) while using the "this" keyword.Of course, you also add the
ActionListenerdirectly (by using.addActionListener(new ActionListener() {});, but by usingthis,you can group all actions together.//edit: Another way would be using
MouseListener, which can listen to any clicks on your object, therefore enabling you to also use swing objects likeJLabelas "buttons" - however, if you useJButtons, this would be unnecessary effort, considering thatActionListeneris way easier to use, and you don't have to create lots of classes (such asmousePressed,mouseClicked,mouseReleased, etc.). However, if you anyway needMouseListenersomewhere, you might want to think about using them so all events are grouped together. Note: I do NOT know ifActionListenerandMouseListenerare equally fast, or if one of these methods are better! If your program requires a lot of power already, you might want to useActionListener, which i guess is the faster way, if any of the two solutions is the faster one.