dimanche 17 février 2019

How or can I generallize an If-statement for multiple JButtons (color changing)?

So I'm trying to make multiple buttons do the same change in color when they are pressed. Each individual press should cycle through a predetermined cycle of colors (White, Red, Green, Yellow, Blue, Black). I could just make a long if-else-statement but for I'm pretty sure there's a better way, I just can't come up with one.

I have already tried "getSource().getBackground()" in the second if-statement but it's not able to get the same variable as the first if-statement does.

 public void actionPerformed(ActionEvent e){   
    if(e.getSource() == btn1){  
      if(getSource().getBackground() == Color.white)  
        setBackground(Color.red);  
        else  
        setBackground(Color.white);  
    }  

As previously stated I'm trying to minimize the effort here and make it also a bit more organized.

Aucun commentaire:

Enregistrer un commentaire