需要一个定时的panel.repaint();

问题描述 投票:0回答:1

我希望我的代码绘制面板,请等待1秒钟。通过执行函数nextGen()编辑面板。并重新粉刷面板。我希望此功能发生5次。问题是,每次我尝试使用thread.sleep()进行尝试/捕获操作时,它都会“跳过”重绘,执行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);
            }
        });
java swing sleep repaint
1个回答
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();

请参阅Concurrency in Swing,以了解出现此特定问题的原因的更多信息,How to Use Swing Timers,以获取有关Swing Timer的更多详细信息,>

© www.soinside.com 2019 - 2024. All rights reserved.