MichaelG
MichaelG

Reputation: 61

GUI using Swing - Trying to get an IF Statement to work with two buttons in the statement

I'm writing a Slot machine GUI and i want it so that The Slot machine will stop Reel 1 and roll reel 2 and 3 when "Respin" is pressed. This code is not working for me please help:

if (event.getSource()== btnHold1)
  {
      counter = 0;   
      timer1.stop();
      btnHold1.setEnabled(false);
  }

  if (event.getSource()== btnHold1 && event.getSource()== btnRespin)
  {
      timer2.start();
      counter2=0;
      timer3.start();
      counter3=0;
  }

Upvotes: 2

Views: 647

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

The condition event.getSource()== btnHold1 && event.getSource()== btnRespin isn't possible. If you only have two buttons, just use an else.

if (event.getSource() == btnHold1) {
    counter = 0;   
    timer1.stop();
    btnHold1.setEnabled(false);
} else {
    timer2.start();
    timer3.start();
    counter3 = counter2 = 0;
}

If you have more than two buttons use an else if like

if (event.getSource() == btnHold1) {
    counter = 0;   
    timer1.stop();
    btnHold1.setEnabled(false);
} else if (event.getSource() == btnRespin) {
    timer2.start();
    timer3.start();
    counter2 = counter3 = 0;
} // else ...

Upvotes: 3

nhouser9
nhouser9

Reputation: 6780

The button source cannot be two different buttons. getSource() checks which button was pressed - you are checking if button1 AND button2 were both pressed at the same time. That can never happen.

I suspect you want your second if to be

if (event.getSource() == btnRespin)

Upvotes: 3

Related Questions