-2

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

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