2017-08-31 40 views
1

當我單擊button1時,button2將變爲紅色,並且當我第二次單擊button1時,button2將變爲黃色。當按鈕2呈藍色時,點擊按鈕1後,按鈕2將變回紅色。我的代碼不正確,但我希望編寫與此類似的代碼。單擊Button1和Button2將根據Java中的順序更改爲多種顏色

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           

    String[] colorsArray = {"red","yellow","green","blue"}; 

    for(int i = 0; i < 4; i++) 
     jButton2.setBackground(Color.colorsArray[i]); 
} 

代碼錯誤:

cannot find symbol

symbol: variable colorsArray

location: class Color

+0

'顏色[] colorsArray = {Color.RED,Color.YELLOW,Color.GREEN, \t \t Color.BLUE};'然後僅'jButton2.setBackground(colorsArray [I]);' –

+1

@ JohnJoe非常感謝你! – Jack

回答

1

編輯:你的顏色陣列是在同一個班,因爲這方法,而不是在一個名爲Color類,如Color.colorsArray所示。代碼固定

您不需要for循環。您需要爲BT2存儲當前狀態,並在達到最終狀態時進行循環。

這樣你從currentColor == 0開始。當你點擊按鈕時,你設置了紅色的BG,設置爲currentColor == 1。下一次,您將其設置爲黃色。當currentColor == 4您將其設置爲0以重新開始。

// put this outside method, as class member 
private final String[] colorsArray = {"red","yellow","green","blue"}; 
private int currentColor = 0; 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
    if (currentColor == colorsArray.length) { 
     currentColor = 0; 
    } 

    jButton2.setBackground(colorsArray[currentColor]); 

    currentColor = currentColor + 1; 
} 
+0

應該是'Color [] colorsArray = {Color.RED,Color.YELLOW,Color.GREEN,Color.BLUE};'而不是'String []' –

+0

@JohnJoe如何獲取顏色文本?就像我的按鈕是綠色的,我想讓文字「綠色」。我試過這個「jButton2.setText((colorsArray [currentColor])。toString());」,但是我得到了'java.awt.Color [r = 0,g = 255,b = 0] – Jack

+0

爲什麼你需要得到文字的顏色? –

1

試試這個

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           

     String[] colorsArray = {"red","yellow","green","blue"}; 

     for(int i = 0; i <= 4; i++) 
      jButton2.setBackground(Color.colorsArray[i]); 
     } 
相關問題