gpt4 book ai didi

java - 如何在 Swing 应用程序中停止计时器

转载 作者:行者123 更新时间:2023-11-30 07:06:39 26 4
gpt4 key购买 nike

我编写了一些代码来更改几个按钮的颜色,以激发随机的闪烁颜色序列。我已经设置了一个计时器来为我执行此操作,但我只是不知道如何停止它

这是我的代码

          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();

最佳答案

有几种方法可以做到这一点,这里有一些快速方法。

一种方法是利用System.currentTimeMillis():

private Timer timer;
private final int DELAY = 100;
private final int DURATION = 10_000;
private long startTime;

public void timerExample() {
timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (System.currentTimeMillis() >= startTime + DURATION) {
System.out.println("Done");
timer.stop();
} else {
System.out.println("Tick");
}
}
});
startTime = System.currentTimeMillis();
timer.start();
}

如果当前时间大于 startTime + DURATION,此函数将停止 Timer

另一种方法是使用计数器:

private Timer timer;
private final int DELAY = 100;
private final int DURATION = 10_000;
private final int TOTAL_TICKS = DURATION / DELAY;
private int tickCounter = 0;

public void timerExample() {
timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (++tickCounter == TOTAL_TICKS) {
System.out.println("Done");
timer.stop();
} else {
System.out.println("Tick");
}
}
});
timer.start();
}

DELAY设为100ms,将DURATION设为10,000ms,您可以计算所需的计时器滴答总数,例如10,000/100 = 100 个刻度。

每次触发 Action 监听器时,它都会检查是否达到了刻度总数,如果达到则停止计时器。

关于java - 如何在 Swing 应用程序中停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com