Thread.sleep() stopping my paint?(Thread.sleep() 停止我的绘画?)
问题描述
我正在制作一个程序,它试图让一张卡片在屏幕上移动,就好像你真的从桌子上画的一样.这是动画的代码:
I'm making a program that is trying to animate a card moving across the screen as if you actually drew it from a desk. Here is the code for the animating:
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 内的面板内.为了重新粉刷面板,我有这个:
this rectangle object is inside of a panel inside of a jframe. for repainting the panel, i have this:
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 毫秒重新绘制一次游戏面板.
this is a thread, repainting the gamePanel every 50 milliseconds.
现在,我意识到这可能不是做这类事情的最佳方式.如果有更好的方法来完成整个重绘,请告诉我!
Now, I realize this may not be the best way to do this sort of thing. if there is a better way to do this whole repainting thing, please inform me!
但是,我遇到的问题是,当我为我的矩形调用 move()
命令时,它会通过线程,但图像直到最后都没有更新,所以它只是一个从a点跳转到最终位置.
But, the problem i'm having is when i call the move()
command for my rectangle, it goes through the thread, but the image isnt updating till the end, so it's just a jump from point a to the final location.
为什么会这样?任何人都可以批评/改进我的代码吗?谢谢!
why is this happening? can anyone critique/improve my code? thanks!
推荐答案
问题是你在 Thread.sleep()/javase/tutorial/uiswing/concurrency/dispatch.html" rel="nofollow">事件调度线程导致 GUI 无响应.为避免这种情况,您可能需要使用 Swing Timer 代替:
The problem is you call Thread.sleep()
in the Event Dispatch Thread causing the GUI become unresponsive. To avoid this you may want to use Swing Timer instead:
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
是一个布尔标志,表示动画必须停止.
Where stop
is a boolean flag that indicates the animation must stop.
这篇关于Thread.sleep() 停止我的绘画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Thread.sleep() 停止我的绘画?


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01