0

I've created a GUI that goes to a new screen (JPanel) when a button is clicked. After this, I would like it to show ImageIcons from an array (1 every few seconds), replacing the old one with the new one. I have seen ways to "pause" the execution for a specified amount of seconds (Thread.sleep()), but this only seems to pause the amount of time between the button being clicked and going to the new screen, only displaying the last image.

I've tried this:

    for(int i = 0; i < array.length(); i++) {
        try{
            Thread.sleep(1000);
            g.drawImage(myImageArray[i]);
        } catch(Exception e) {
           System.out.println("Exception caught");
        }
    }

With no luck. Any suggestions?

Micho
  • 3,929
  • 13
  • 37
  • 40
merp
  • 1
  • That's because you are doing all processing in the same thread. You should do all processing in a separate thread and GUI updates in a separate thread (called Event Dispatching Thread). Take a look at [Swing Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/) – Codebender Jun 19 '15 at 03:17
  • 1
    See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) and use a Swing `Timer` instead, [How to use Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html), for [example](http://stackoverflow.com/questions/24111940/how-to-update-a-jframe-in-a-second-window/24112256#24112256) – MadProgrammer Jun 19 '15 at 03:19
  • Look at Mad's answer [here](http://stackoverflow.com/questions/13870982/updating-swing-components-correctly) and also [here](http://stackoverflow.com/questions/13870982/updating-swing-components-correctly). – Hovercraft Full Of Eels Jun 19 '15 at 03:28
  • MadProgrammer is right. Use Timers instead of sleeping the thread. – STaefi Jun 19 '15 at 03:59
  • Thank you all! Will look into it – merp Jun 19 '15 at 09:49
  • I can't figure out how to use the actionPerformed method, do I have to loop inside of the method or before or after? `Timer tm = new Timer(500,new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for(int i = 0; i < 10; i++){ g.drawImage(photos[i].getImage(),(900/2)-(photos[i].getIconWidth()/2), (600/2)-(photos[i].getIconHeight()/2), photos[i].getIconWidth(), photos[i].getIconHeight(), null); } } }); ; tm.start();` – merp Jun 19 '15 at 23:32

0 Answers0