我有5個JButton:b1,b2,b3,b4,b5。 默認情況下,它們的顏色是灰色的。 當我點擊任何按鈕時,該按鈕的背景變成白色。 當我點擊另一個按鈕時,我希望先前單擊的按鈕將其背景更改爲灰色,並且此新近單擊的按鈕將其背景更改爲白色。這裏是我寫的代碼:設置Jbutton的背景
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));
}
但是,它沒有按預期工作。當我點擊一個按鈕時,它的背景會變成白色。但是,如果在此之後點擊其他按鈕,則前一個按鈕的背景不會變爲灰色。我嘗試更換Color.GREY與新java.awt.Color(236,233,216) - rgb爲灰色但它仍然無法正常工作。
你想模擬一個ButtonGroup的功能嗎?例如只有一個按鈕可以選擇/切換? btw:用java.awt.Color.white替換new java.awt.Color(255,255,255) – Tedil 2010-04-11 17:41:10
yes!但我並沒有意識到ButtonGroup的存在。我認爲buttongroup只適用於單選按鈕。 – mithun1538 2010-04-12 20:22:24