Home > other >  Updating a JPanel automatically after specified time
Updating a JPanel automatically after specified time

Time:09-27

I have a JPanel and I want it to update after a specified time interval. I tried using Thread.sleep but it doesn't work.

Let's say I want it to be updated after 5 seconds, so I first create the JFrame and then add the initial JPanel with the initial components and then I add Thread.sleep(5000); after which I add another component. But when I ran the code, all it showed was a blank frame for 5 seconds and then it just added the JPanel with all the components, including the one which was to be added after a delay.

I want to know why does this method doesn't work and how can I achieve the desired result using repaint() as I didn't find any useful tutorials for repaint()

P.S.- Sorry if the question was dumb but I am a newbie and just want to understand the reason why does this approach not work

CodePudding user response:

The initial thread is your main application. Use that to initialize the UI. After that you have at least two different threads: The main thread, which often is left to terminate, and the Event Dispatching Thread (EDT) which is used to manage the UI and handle all the events.

What you can do is to use your main thread, or worker threads that your application needs to spawn to trigger events. See Timer to trigger events every x seconds.

Now when the Timer's ActionListener runs, it is running on the timer thread. Some UI updates are better done on the EDT, and that is when work needs to be handed over. In such cases do not modify your UI from the timer or the main thread directly but dispatch the work using SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater().

  • Related