gpt4 book ai didi

java - 在指定时间内执行部分代码

转载 作者:行者123 更新时间:2023-12-01 23:11:37 25 4
gpt4 key购买 nike

我想使用java swing制作动画。我有一个 for 循环,可以稍微改变图像的位置。我的问题是如何使每个循环执行花费指定的时间?。这就是我所做的,但我不知道如何使用 wait() 并且不知道是否有更好的方法。

// inside of a MyJPanel class extending JPanel
for (int i = 0; i < FJframe.FRAMES; i++){
long start = System.currentTimeMillis();
animationFrame = i;
this.repaint();
long end = System.currentTimeMillis();
long remainder = (end - start);
System.out.println(remainder);
try {
this.wait(200 - remainder);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
<小时/>

编辑

这里是我重写的 Jpanel PaintComponent(): //一些绘图 drawChanges(g, getDelta(),animationFrame, FJPanle.FRAMES);

在drawChanges(Graphics g, ArrayList deltas, intframe, intframes)内部:

// a switch_case with cases similar to this one.
case AGENT_ATTACK:
// tu phase badi animation e kill
//drawImage(g2d, map[delta.getCell().x][delta.getCell().y], attacker);
source = map[delta.getSource().x][delta.getSource().y];
dest = map[delta.getDestination().x][delta.getDestination().y];
distanceX = dest.getCenter().x -
source.getCenter().x;
distanceY = dest.getCenter().y -
source.getCenter().y;
if (counter < frames / 2){
g2d.drawImage(ImageHolder.attacker, source.getBounds().x + (int)(((float)counter/frames) * distanceX),
source.getBounds().y + (int)(((float)counter/frames) * distanceY),
null);
}
else{
g2d.drawImage(ImageHolder.attacker, dest.getBounds().x - (int)(((float)counter/frames) * distanceX),
dest.getBounds().y - (int)(((float)counter/frames) * distanceY),
null);
}
break;
<小时/>

例如,我希望每个循环恰好花费 200 毫秒。我怎样才能实现这个目标?

最佳答案

考虑使用Timer 。例如,scheduleAtFixedRate()方法。

关于java - 在指定时间内执行部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21860153/

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