I'm trying to creat simple seating for movie
I have the seats as buttons when the user click btnOne then the background change to red if the user click the button again it will chnage to gray
I've managed to change the color to red when it clicked using actionpreformed , but how can I change it to gray when it clicked again

  if( btnOne.isSelected() == false){
       btnOne.setBackground(Color.RED);
       res = true; 
   } 

I've also tried this but it doesnt' work

       if( btnOne.isSelected() == false){
       btnOne.setBackground(Color.RED);
       btnOne.setSelected(true);
   } 

   if(btnOne.isSelected() == true){
     btnOne.setBackground(Color.black);
       btnOne.setSelected(false);

  }

Edited 2 Years Ago by sk8ergirl

a few remarks. a few small refactorings, to make your code in less lines, and more readable.

if ( btnOne.isSelected() == true )
this is actually the exact same as:
if ( btnOne.isSelected() )

and it's better to use an if-else statement, rather than two ifs. that way, your value will be only tested once, against the two times it is tested now.

since the btnOne setSelected is basically the same for both, you can write your code like this:

if ( btnOne.isSelected()){
  btnOne.setBackground(Color.black);
}
else{
  btnOne.setBackground(Color.RED);
}
btnOne.setSelected(!btnOne.isSelected());

less work, less chances for mistakes and easier to read :)

now, IMHO, using the selected variable for the JButton is not the right way to go. I would use a variable in the class where the JButton is declared, for instance:

private boolean buttonClicked = false; // original default value

@Override
public void actionPerformed(ActionEvent event){
  if ( event.getSource() == btnOne ){
    if ( buttonClicked ){
      // it's clicked now.
      btnOne.setBackground(Color.RED);
    }
    else{
      btnOne.setBackground(Color.BLACK);
    }
    buttonClicked = !buttonClicked;
  }
  // code for any other components that might have an actionlistener
}
This article has been dead for over six months. Start a new discussion instead.