gpt4 book ai didi

java - 了解 Swing 计时器

转载 作者:行者123 更新时间:2023-12-01 17:25:34 24 4
gpt4 key购买 nike

我有这个计时器用于通过 JFrame 和 JPanel 移动 Star.png

移动带有计时器的星星的函数:

private final static int HEIGHT = 300;
.
.//more code here
.
.
x=y=0;
.
.

public void downRight() {
Timer localTimer = new Timer(100, null);
localTimer.setRepeats(false);
localTimer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x++;
y++;
repaint();
}
});
int xTest=0;
while (y < HEIGHT) {
System.out.println("x "+(++xTest)+" y "+y);
localTimer.start();
}
System.out.println("Reached");
}

运行计时器并测试 xTest 时,发现 y 值如下:

x 1 y 0

x 2 y 0

x 3 y 0

..... More Outputs here

.....

x 1653 y 1

x 1654 y 1

......

......

x 285836 y 299

x 285837 y 299

Reached

那么这里发生了什么?为什么xTesty大太多,尽管两者在同一范围内?

最佳答案

xTesty 没有相同值的原因是 Timer 具有 initial delay (设置为构造函数中提供的延迟)。调用 start 后需要 100 毫秒,y 的值才会增加 1。在此期间,xTest 被允许尽可能快地增加。

关于java - 了解 Swing 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179603/

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