Thread.sleep() 停止我的绘画? [英] Thread.sleep() stopping my paint?

查看:43
本文介绍了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!

推荐答案

问题是你在 事件调度线程导致 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() 停止我的绘画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆