Thread.sleep() stopping my paint?

后端 未结 2 1828
时光说笑
时光说笑 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.

提交回复
热议问题