我有 5 个 JButton:b1、b2、b3、b4、b5。默认情况下,它们的颜色为灰色。当我单击任何按钮时,该按钮的背景变为白色。当我单击另一个按钮时,我希望之前单击的按钮将其背景更改为灰色,而这个新单击的按钮将其背景更改为白色。这是我写的代码:
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));
}
但是,它没有按预期工作。当我单击一个按钮时,它的背景确实变为白色。但是,如果我在那之后单击其他按钮,则前一个按钮的背景不会变为灰色。我尝试用新的 java.awt.Color(236,233,216) 替换Color.GREY - RGB 为灰色,但它仍然不起作用。