【发布时间】:2016-10-12 15:54:25
【问题描述】:
我写了一个小代码来改变几个按钮的颜色来激发随机序列的闪烁颜色。我已经为我设置了一个计时器,但我只是不知道如何停止它
这是我的代码
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int buttons[] = new int[9];
for (int j = 0; j < buttons.length; j++) {
// System.out.println("times");
Component button = frame.getContentPane().getComponent(j);
int Red = new Random().nextInt(255 - 1) + 1;
int Green = new Random().nextInt(255 - 1) + 1;
int Blue = new Random().nextInt(255 - 1) + 1;
button.setBackground(new Color(Red, Green, Blue));
SwingUtilities.updateComponentTreeUI(button);
}
}// }
}); timer.start();
【问题讨论】:
-
您需要在 Timer 对象上调用 stop() 方法。您希望它何时/如何停止?
-
创建一个变量。然后在定时器滴答时增加它。当变量值达到8时停止定时器
-
@fastsnil 我试图创建一个整数变量 counter 并在 for 循环中递增它但不起作用,你能告诉我你的代码是什么意思吗?
-
对于example。
-
不要使用
updateComponentTree(...)!!!没有必要使用这种方法。您需要做的就是调用 setBackground() 方法,组件将自行重新绘制。increment it in the for loop but doesn't work,- 不,你不会在 for 循环中增加它。在 actionPerformed() 方法的末尾增加它。然后当达到 10 时停止计时器。
标签: java swing timer timertask