Hello there,
I have 5 JButtons: b1, b2, b3, b4, b5.
By default, their color is gray.
When I click on any button, the background of that button changes to white.
When I click another button, I want that previous clicked button to change its background to gray, and this newly clicked button to change its background to white. Here is the code that I wrote:
int liveButton = 0; //holds the value of the button that is last clicked.
//0 indicates no button clicked (in the beginning)
private void ChangeInUsersList(int clickedButton) {
switch(liveButton) {
case 1 : b1.setBackground(Color.GRAY);
break;
case 2 : b2.setBackground(Color.GRAY);
break;
case 3 : b3.setBackground(Color.GRAY);
break;
case 4 : b4.setBackground(Color.GRAY);
break;
case 5 : b5.setBackground(Color.GRAY);
break;
default: System.out.println("No button to change");
}
liveButton = clickedButton;// store the clicked button to change its
//background later
}
private void b1ActionPerformed(java.awt.event.ActionEvent evt) {
ChangeInUsersList(1);
b1.setBackground(new java.awt.Color(255,255,255));
}
private void b2ActionPerformed(java.awt.event.ActionEvent evt) {
ChangeInUsersList(2);
b2.setBackground(new java.awt.Color(255,255,255));
}
private void b3ActionPerformed(java.awt.event.ActionEvent evt) {
ChangeInUsersList(3);
b3.setBackground(new java.awt.Color(255,255,255));
}
private void b4ActionPerformed(java.awt.event.ActionEvent evt) {
ChangeInUsersList(4);
b4.setBackground(new java.awt.Color(255,255,255));
}
private void b5ButtonActionPerformed(java.awt.event.ActionEvent evt) {
ChangeInUsersList(5);
b5.setBackground(new java.awt.Color(255,255,255));
}
However, its not working as expected. When i click on a button, its background does change to white. However, if i click on some other button after that, the former button's background doesnt change to grey. I tried replacing Color.GREY with new java.awt.Color(236,233,216) - the rgb for grey but it still doesnt work.