我正在尝试使用更多的GUI,但我遇到了问题。我有一系列JLabel。它们每个都包含1到0到7的数字。我通过将背景颜色从黑色变为绿色来使数字“亮起”。是否有任何方法可以使所有偶数“亮起”同时保持所有奇数变暗,反之亦然?我尝试使用计时器,但我的算法不能正常工作。下面是配置计时器的方法的代码。感谢
public void configureAlternatingTimer() {
if (this.timer != null) {
this.timer.stop();
}
this.timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i <= 8; i++) {
if (i == 0 || i == 2 || i == 4 || i == 6) {
lights[1].setBackground(Color.black);
lights[3].setBackground(Color.black);
lights[5].setBackground(Color.black);
lights[7].setBackground(Color.black);
lights[i].setBackground(Color.green);
}
if (i == 1 || i == 3 || i == 5 || i == 7) {
lights[0].setBackground(Color.black);
lights[2].setBackground(Color.black);
lights[4].setBackground(Color.black);
lights[6].setBackground(Color.black);
lights[i].setBackground(Color.green);
}
if(i==8) {
return;
}
}
}
});
this.timer.start();
}
此外,我正在尝试模拟一个“larson扫描仪”,它会点亮7然后再回到0然后重复。我可以让它从0到7,这只是我遇到麻烦的回归部分。感谢
答案 0 :(得分:0)
删除for-loop
,阻止事件调度线程处理repaint
个请求
相反,每次调用actionPerformed
方法时,请更新某种计数器,然后对其采取措施,例如......
this.timer = new Timer(100, new ActionListener() {
private int sequence = 0;
public void actionPerformed(ActionEvent evt) {
if (sequence % 2 == 0) {
lights[1].setBackground(Color.black);
lights[3].setBackground(Color.black);
lights[5].setBackground(Color.black);
lights[7].setBackground(Color.black);
lights[sequence].setBackground(Color.green);
} else {
lights[0].setBackground(Color.black);
lights[2].setBackground(Color.black);
lights[4].setBackground(Color.black);
lights[6].setBackground(Color.black);
lights[sequence].setBackground(Color.green);
}
sequence++;
if (sequence > 7) {
// This seems to be important...?
}
}
});
根据评论更新
这应该显示所有可能性或所有均衡......
Timer timer = new Timer(500, new ActionListener() {
private int sequence = 0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(sequence + "; " + (sequence % 2));
for (int index = 0; index < lights.length; index++) {
if (index % 2 == 0 && sequence % 2 == 0 || index % 2 != 0 && sequence % 2 != 0) {
lights[index].setBackground(Color.GREEN);
} else {
lights[index].setBackground(Color.BLACK);
}
}
sequence++;
if (sequence > 7) {
sequence = 0;
}
}
});
答案 1 :(得分:0)
要确定您是偶数还是奇数,您应该考虑使用模数运算符%来确定数字是奇数还是偶数。模数将在分割后返回数字的余数。
For example:
4 / 2 = 2r0
5 / 2 = 2r1
6 / 2 = 3r0
7 / 2 = 3r1
so on and so forth...
if(i % 2 == 0) {
// even
} else {
// odd
}