Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)?

like image 573
cvbattum Avatar asked Apr 28 '13 19:04

cvbattum


2 Answers

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).

like image 125
syb0rg Avatar answered Nov 06 '22 07:11

syb0rg


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.
like image 45
Hovercraft Full Of Eels Avatar answered Nov 06 '22 07:11

Hovercraft Full Of Eels