我正在制作一个程序,尝试为一张在屏幕上移动的卡片设置动画,就像您实际上从 table 上绘制它一样。这是动画代码:
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点跳转到最终位置。
为什么会发生这种情况?任何人都可以批评/改进我的代码吗?谢谢!
最佳答案
问题是您在 Event Dispatch Thread 中调用 Thread.sleep()
导致 GUI 变得无响应。为了避免这种情况,您可能需要使用 Swing Timer相反:
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();
其中stop
是一个 boolean 标志,指示动画必须停止。
关于java - Thread.sleep() 停止我的绘画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840492/