Thread.sleep() stopping my paint?

痴心易碎 提交于 2019-11-28 13:11:53

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();

Where stop is a boolean flag that indicates the animation must stop.

Most probably, the forloop in method move() is running so fast you don't see any transitions. The simplest way to solve this is adding a sleep within the loop in the move() method, such as:

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;
        Thread.sleep(20); // Just experiment with other sleep amounts
    }
    this.x = x;
    this.y = y;
}

Regarding the repainting logic, it is generally inefficient to have a separate thread redraw everything at each cycle, mainly because you could be repainting things that haven't actually changed. It is usually more efficient to update only the things that change.

In a complex situation in which several shapes overlap each other, you would need to determine what changes and what doesn't, because if something doesn't move but is overlapped by something that does, you would need to update the overlapped shape as well to ensure it is drawn correctly. There are sofisticated algortihms that address just this problem, but if your scene does not have many shapes then it could be simpler to just redraw everything when something changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!