I am currently creating a game in Java using Swing. I have a button, and once it does one thing, I want it's action to change. I have tried if statements, if-else statements, while loops, and various other things, and I can't get it to work. Anyone know how to do something like this?
Asked
Active
Viewed 72 times
-2
-
1Everyone knows how to do something like this. You need to provide a bit more info (and probably code) so we can help you out... – John3136 Jan 08 '14 at 01:10
-
1Change the `ActionListener` as required... – MadProgrammer Jan 08 '14 at 01:12
2 Answers
4
Create a class level attribute along the lines of:
boolean buttonHasFiredOnce = false;
In the action performed method, put code like:
if (!buttonHasFiredOnce) {
doFirstMethod();
buttonHasFiredOnce = true;
} else {
doSecondMethod();
}

Andrew Thompson
- 168,117
- 40
- 217
- 433
-
If you cannot get it to work from that tip: post an [SSCCE](http://sscce.org/) of your best attempt. It should only require about 20 lines of code. – Andrew Thompson Jan 08 '14 at 01:14
0
I would suggest replacing the ActionListener
public static void changeAction(JButton button, ActionListener al) {
for (ActionListener listener: button.getActionListeners()) {
button.removeActionListener(listener);
}
button.addActionListener(al);
}
then when you want the action to change...
changeAction(button, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Insert Action Code
}
});

jpdymond
- 1,517
- 1
- 8
- 10