Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing UI not updating after using invokeLater

I have a Java Swing UI that isn't updating/repainting as I thought it should. The app sends an XMPP message and receives a response on a different thread. That response is processed and the UI is updated to reflect information contained in the message.

When the response is received, I update a JPanel component using

javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() { /* execute logic to update panel */ }
});

It's been quite sometime since I've developed in Java, but based on my research online invokeLater queues the runnable up for execution on the GUI thread. However, my GUI doesn't update until I do something else in the app that causes a repaint - such as resizing the window. What am I missing? After the logic for updating the panel, I've tried various combinations of invalidate() and repaint(), but the result is still the same - the GUI does not update until I, say, resize the window.

EDIT: When I say updating the panel, I am, specifically, doing a removeAll() and then adding a handful of JLabels.

like image 409
Matt Avatar asked Jul 24 '09 15:07

Matt


People also ask

How do you refresh a Swing GUI?

In Swing you should never have to do what you are asking manually, you just update the models and the screen gets updated automatically.

How do you update Swing component from a thread other than EDT?

You can use invokeAndWait() and invokeLater() to update a Swing component from any arbitrary thread.

What is SwingUtilities invokeLater () used for?

An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.

What is the what is the difference between InvokeAndWait() and invokeLater()?

Difference on InvokeLater vs InvokeAndWait in Swing 1) InvokeLater is used to perform a task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously. 2) InvokeLater is a non-blocking call while InvokeAndWait will block until the task is completed.


1 Answers

After adding/removing components from a panel you should use:

panel.revalidate(); // this works 99% of the time
panel.repaint(); // sometimes needed.

Other stuff like validate(), invalidate() etc., is left over from AWT days I believe and revalidate() does a better job and was added specifically for Swing.

like image 176
camickr Avatar answered Nov 08 '22 10:11

camickr