OS : Windows XP
JDK : JDK 1.4
The code looks like,
saveButton.addActionListener(new MyActionListener());
....
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == saveButton) {
<some code>
}
}
}
Here the <some code> is executed twice. But this is not repetable always.
hi
i have tried with your code, works fine with me, 100 on 100, my pc is windows xp(sp2) amd xp, jdk1.4. i could not simulate the problem. what you can do, is just check to make sure that whether you have added saveButton.addActionListener(new MyActionListener()); twice or not.
i guess it is a huge project, so may be from some other place even some other code posts a event in event dispatch thread, i am not sure, i faced this once.
regards
Aniruddha
This is only a stylistic point, and probably won't help you solve your problem. That being said...
In the code you posted, you've declared a private class MyActionListener, and are creating a new instance of that class in the button's .addActionListener(). In MyActionListener, you're testing the source to see what action to take (which button was pressed).
IME, I usually use one of two patterns for ActionListeners:
1. Declare my form (or whatever) to implement ActionListener. Pass 'this' to .addActionListener() method on all buttons. Test which button was pressed inside actionPerformed().
OR
2. Declare an Action extending AbstractAction. Pass a new instance of this Action to the ONE button (or whatever) that will cause it to fire. No need to test for source, since you know where it came from (or don't care, as in the case where you have both a regular button and a menu item that perform the same Action).
I'm not sure I'm seeing the benefit of loading another class (your private class) to perform handling that's typically performed in the regular class that extends ActionListener. And potentially, you're loading many extra classes, since you're likely issuing '.addActionListener(new MyActionListener())' for every button (going by your example).