2016-12-08 63 views
-4

我有20個按鈕,我想要改變所有按鈕的顏色,當我點擊一個特殊的按鈕,有沒有辦法做到這一點與功能(或沒有功能),不要使用的setBackground 20次更改java中的所有按鈕顏色

+1

爲什麼不使用循環? – ItamarG3

+0

''並且不要使用setBackground 20次'' - 請證明這一點。正確的做法是@ItamarGreen指出,將所有按鈕放置在一個集合中,比如一個ArrayList,並且,可以在循環中創建20個'setBackground(...)'調用。 –

+1

你的陳述事實上表明你可能會把馬車放在馬前。 –

回答

1

你可以把按鈕放在一個陣列

JButton[] array = new JButton[20]; 
//then add the buttons to the array 

然後:

for(JButton button : array){ 
    button.setBackground(/*the color you want*/); 
} 
1

你不應該做button1button2

相反,做一個List<Button> buttons。您仍然需要在該列表上撥打add() 20次,但是您可以將它們全部循環。

for (Button b : buttons) { 
    b.setBackground(color); 
}