需要定时 panel.repaint();

Need a timed panel.repaint();

我想让我的代码绘制面板,请等待 1 秒。通过执行函数 nextGen() 来编辑面板;并重新粉刷面板。我希望这个功能发生 5 次。问题是,每次我尝试用 thread.sleep() 做一件 try/catch 事情时,它 "skips" 重绘,执行 nextGen();和睡觉。请帮忙!

button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                for(int i = 0;i<5;i++) {
                    try {
                        Thread.sleep(1000);
                        nextGen();
                        panel.repaint();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                //System.exit(0);
            }
        });

使用秋千Timer...

Timer timer = new Timer(1000, new ActionListener() {
    private int count;
    @Override
    public void actionPerformed(ActionEvent evt) {
        nextGen();
        panel.repaint();
        count++;
        if (count >= 5) {
            ((Timer)evt.getSource()).stop();
        }
    }
});
timer.start();

有关 Swing 的更多详细信息,请参阅 Concurrency in Swing for more information about the reason why you're having this particular issue and How to Use Swing Timers Timer