1

I have to change the the icon of a jLabel every 2 seconds. I use a Timer and a Timer task to do this, but it only shows the first image. Here is the code:

    ImageIcon[] icons = {new ImageIcon(this.getClass().getResource("orange.jpg")), new     
    ImageIcon(this.getClass().getResource("cosmote.jpg")), new 
    ImageIcon(this.getClass().getResource("vodafone.jpg"))};
    java.util.Timer timer = new java.util.Timer();
    int indexIcon;

And then in the JFrame constructor:

    initComponents();
    open(fisierAgenda);
    TimerTask task = new TimerTask() {
        public void run() {
            indexIcon=(indexIcon++)%3;
            jLabel.setIcon(icons[indexIcon]);
            jLabel.setText(""+indexIcon);
        }
    };
    timer.schedule(task, 0, 2000);

Any help would be much appreciated.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Cristi Ionut
  • 63
  • 2
  • 9
  • Implement a **Swing** `Timer` for repeating tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. See also this [working example](http://stackoverflow.com/a/13512826/418556). – Andrew Thompson May 22 '13 at 13:01

2 Answers2

3
  • you have an issue with Concurency in Swing

  • Swing is Single Threaded and all events must be done on EDT

  • output from util.Timer never will be notifyed Event Dispatch Thread, without any changes to the already visible Swing GUI

  • use Swing Timer, then output will be always done on EDT

mKorbel
  • 109,525
  • 20
  • 134
  • 319
-1

You should use a thread for this. At least, that's what I would use.

  • 1
    Not the down-voter, but all edits and updates to Swing GUIs should be on the EDT. – Andrew Thompson May 22 '13 at 13:03
  • 1
    Not the down-voter either but: 1) All updates should be done on the EDT (so the simplest thing is to use a Swing Timer) 2) Since Java 1.5, you are better off using the `Executors` framework rather than create `Thread`'s manually. 3) If needed, you can combine `Executors` and `SwingUtilities.invokeLater()` – Guillaume Polet May 22 '13 at 13:16