cvbattum
cvbattum

Reputation: 799

Reload JPanel every X seconds (with threads?)

I have a settings tab in my program. The data you can set there, is not only changeable from this panel. That's why I want to reload this data like every 5 seconds. I think this has to be done with an extra Thread, but my knowledge about Threads is minimal. I already have a reload method for this purpose.

What should I use to do this (and how...)?

Upvotes: 5

Views: 765

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

but my knowledge about Threads is minimal...

  1. You absolutely need to learn about threads in general, and the Java Concurrency Tutorial can help.
  2. Then you should learn about concurrency in Swing in particular.
  3. Draw your GUI's graphic representation of the data in your JPanel's paintComponent(...) method, or perhaps better, in a BufferedImage that is then displayed inside of paintComponent(...).
  4. Reload the data in a background thread such as a SwingWorker. This Worker can have a java.util.Timer or a ScheduledExecutorService as per syb0rg's answer (1+ to syb0rg's answer) that requests and obtains new data every 5 seconds.
  5. Then call repaint() from the Swing event thread after your data is changed. If using a SwingWorker, the process/publish method pair could help with this. You could publish your data to the Swing event thread with this.

Upvotes: 5

syb0rg
syb0rg

Reputation: 8247

Use a ScheduledExecutorService:

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 5, 5, SECONDS);

Then reload your JPanel in yourRunnable (just follow the example from the JavaDocs).

Upvotes: 5

Thierry
Thierry

Reputation: 5233

You could use Timer to update periodically your data.

Upvotes: 0

Related Questions