2017-10-17 8 views
0

メソッド内で4つのボタンを色から変更しようとしていますが、他のボタンの1つを押してもカウンタがオンになり、すべてのボタンがそれ自身でカウントされ、ボタンが停止しました。メソッドでボタンの色を変更するにはどうすればよいですか?

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

あなたは "すべてのカウンタ" とはどういう意味ですか?コードには1つのカウンタ変数しかありません。すべてのボタンに1つずつ追加する場合は、ボタンごとに1つずつ宣言する必要があります。 –

+0

ボタンの色をクリックして変更しますか? – Russiancold

+0

= 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; 
     //............ 
    } 
関連する問題