当我点击button1时,button2将变为红色,当我第二次点击button1时,button2将变为黄色。当button2为蓝色时,单击button1后,button2将变回红色。我的代码不正确,但我希望编写与此类似的代码。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] colorsArray = {"red","yellow","green","blue"};
for(int i = 0; i < 4; i++)
jButton2.setBackground(Color.colorsArray[i]);
}
代码错误:
无法找到符号
symbol:variable colorsArray
location:class Color
答案 0 :(得分:1)
试试这个
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] colorsArray = {"red","yellow","green","blue"};
for(int i = 0; i <= 4; i++)
jButton2.setBackground(Color.colorsArray[i]);
}
答案 1 :(得分:1)
编辑:您的颜色数组与此方法属于同一个类,而不是名为Color的类,如Color.colorsArray代码所示。代码已修复
您不需要for
循环。您需要存储BT2的当前状态,并在到达结束时循环。
这样你就可以从currentColor == 0
开始。单击按钮时,设置红色BG,设置currentColor == 1
。下次,将其设置为黄色。当currentColor == 4
将其设置为0以重新开始时。
// put this outside method, as class member
private final String[] colorsArray = {"red","yellow","green","blue"};
private int currentColor = 0;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (currentColor == colorsArray.length) {
currentColor = 0;
}
jButton2.setBackground(colorsArray[currentColor]);
currentColor = currentColor + 1;
}