Thread.sleep() 停止我的绘画?

2022-01-24 00:00:00 multithreading graphics java swing jframe

我正在制作一个程序,它试图让一张卡片在屏幕上移动,就好像你真的从桌子上画的一样.这是动画的代码:

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.

相关文章