简体   繁体   English

如何或可以概括多个JButton的If语句(颜色变化)?

[英]How or can I generalize 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. 我可以做一个很长的if-else语句,但是因为我很确定有更好的方法,我只是想不出一个方法。

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. 我已经在第二个if语句中尝试过“ getSource()。getBackground()”,但是它无法获得与第一个if语句相同的变量。

 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. 如前所述,我正在尝试最小化这里的工作并使它更有条理。

A possible solution would be something like: 可能的解决方案是这样的:

  1. Initialize a "button-pressed" counter. 初始化“按钮按下”计数器。 So have a variable outside your actionPerformed method and increment it everytime the button is pressed. 因此,请在actionPerformed方法外部设置一个变量,并在每次按下按钮时将其递增。 Add some logic to reset the counter value once it exceeds a certain threshold, ie after you cycled through your "last" colour, return to the first color. 添加一些逻辑值以在计数器值超过某个阈值时将其重置,即,在循环选择“最后”颜色之后,返回到第一种颜色。
  2. Have a switch statement, which would set the background according to the value of the counter (essentially, how many times the button was pressed). 有一个switch语句,它将根据计数器的值(本质上是按钮被按下的次数)设置背景。

What I would do is make a function that checks and changes background and then pass all my buttons to it. 我要做的是创建一个检查和更改背景,然后将所有按钮传递给它的功能。

public void checkAndChangeColor(Object source, Object btn, int bgToCheck, int bgToChange1, int bgToChange2){
    if (source == btn) {
        if (source.getBackground() == bgToCheck)
            setBackground(bgToChange1);
        else
            setBackground(bgToChange2);
    }
}

and then I would call that method on every button. 然后我将在每个按钮上调用该方法。

checkAndChangeColor(e.getSource(), btn, Color.white, Color.red, Color.white);

Make a private inner class that implements ActionListener and have a collection of colors inside it. 制作一个私有内部类,该类实现ActionListener并在其中包含颜色的集合。 Override actionPerformed and have an internal count so e.setBackground(colorList.get(count % colorList.size()) 覆盖actionPerformed并且具有内部计数,因此e.setBackground(colorList.get(count%colorList.size())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM