[英]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: 可能的解决方案是这样的:
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.