2017-10-17 28 views
0

我想從方法中的顏色改變4個按鈕,但是即使我按下其他按鈕之一,計數器也會繼續,並且我希望每個按鈕都會計算出它自身,並從0開始而不是從另一個位置開始按鈕已停止。如何在方法中改變按鈕的顏色?

int count = 0; 

public void ColourChange(JButton jButtonColour1){ 
    //Changes the colours of the buttons, doesn't work good because it goes on counting for the other buttons too. 

    //returns the counter to 0 after it gets to 10. 
    if (count >= 10) { 
     count = 0; 
    } 
    count++; 

    //Makes sure it can be used at all the 4 buttons instead on just 1. 
    JButton setColour = jButtonColour1, jButtonColour2, jButtonColour3, jButtonColour4; 

    Color color; 

     switch (count) { 
      case 1: 
       count = 1; 
       setColour.setBackground(Color.BLACK); 
       break; 
      case 2: 
       count = 2; 
       setColour.setBackground(Color.RED); 
       break; 
      case 3: 
       count = 3; 
       setColour.setBackground(Color.PINK); 
       break; 
      case 4: 
       count = 4; 
       setColour.setBackground(Color.GREEN); 
       break; 
      case 5: 
       count = 5; 
       setColour.setBackground(Color.BLUE); 
       break; 
      case 6: 
       count = 6; 
       setColour.setBackground(Color.YELLOW); 
       break; 
      case 7: 
       count = 7; 
       setColour.setBackground(Color.MAGENTA); 
       break; 
      case 8: 
       count = 8; 
       setColour.setBackground(Color.cyan); 
       break; 
      case 9: 
       count = 9; 
       setColour.setBackground(Color.GRAY); 
       break; 
      case 10: 
       count = 10; 
       setColour.setBackground(Color.ORANGE); 
       break; 
     } 
} 
+0

你是什麼意思 「每個櫃檯」?代碼中只有一個計數器變量。如果你想爲每個按鈕都有一個按鈕,則需要爲每個按鈕聲明一個按鈕。 –

+0

你想通過點擊來改變你的按鈕顏色嗎? – Russiancold

+0

count = 1,count = 2等在交換機中是沒有意義的。想想爲什麼。 – Russiancold

回答

0
string buttonName=""; 
public int ColourChange(JButton jButtonColour1,int count){ 
//some codes 
if(!(buttonName.equals(jButtonColour1.getText()))){ 
    buttonName=jButtonColour1.getText();//name or what are u using 
    count = 0; 
} 
//some codes 
switch (count) { 
     case 1: 
      count = 1; 
      setColour.setBackground(Color.BLACK); 
      break; 
     case 2: 
      count = 2; 
      setColour.setBackground(Color.RED); 
      break; 
     //............ 
    }