我正在制作一个程序,尝试为一张在屏幕上移动的卡片设置动画,就像您实际上从桌子上绘制它一样。这是动画的代码:
public void move(int x, int y) {
int curX = this.x; //the entire class extends rectangle
int curY = this.y;
// animate the movement to place
for (int i = curX; i > x; i--) {
this.x = i;
}
this.x = x;
this.y = y;
}
该矩形对象位于 jframe 内的面板内。为了重新绘制面板,我有这个:
public void run() {
while (Core.isRunning()) {
gamePanel.repaint(); //panel in which my rectangle object is in
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这是一个线程,每 50 毫秒重新绘制一次 gamePanel。
现在,我意识到这可能不是做这类事情的最佳方式。如果有更好的方法来完成整个重画工作,请告诉我!
但是,我遇到的问题是当我打电话时move()
命令我的矩形,它通过线程,但图像直到最后才更新,所以它只是从点 a 跳转到最终位置。
为什么会发生这种情况?任何人都可以批评/改进我的代码吗?谢谢!
问题是你打电话Thread.sleep()
in the 事件调度线程 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html导致 GUI 变得无响应。为了避免这种情况,您可能需要使用摇摆计时器 http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html反而:
Timer timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!stop) {
gamePanel.repaint();
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setDelay(50);
timer.start();
Where stop
是一个布尔标志,指示动画必须停止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)