0

I want my code to paint a panel, wait 1 second. Edit the panel by executing the function nextGen(); and repaint the panel. I want this function to happen 5 times. The problem is, everytime I try to do a try/catch thing with thread.sleep(), it "skips" over repaint, does nextGen(); and sleeps. Please help!

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);
            }
        });
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

1 Answers1

0

Use a Swing 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();

See Concurrency in Swing for more information about the reason why you're having this particular issue and How to Use Swing Timers for more details about Swing Timer

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366