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);

  }

Recommended Answers

All 2 Replies

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
}

Try to use JToggleButton instead of using JButton.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.