2017-10-17 81 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; 
     //............ 
    }