Thread.sleep() stopping my paint?

后端 未结 2 1824
时光说笑
时光说笑 2020-12-11 13:58

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:

p         


        
相关标签:
2条回答
  • 2020-12-11 14:36

    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.

    0 讨论(0)
  • 2020-12-11 14:41

    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.

    0 讨论(0)
提交回复
热议问题