I’m working in Java, and I have a JPanel in a JFrame. In that JPanel, among other things, I have a JLabel that I want to make appear and disappear at will. I’ve tried setting visibility to true/false, adding and removing it from the JFrame and JPanel, and, having looked online, I tried validate()ing and revalidate()ing ad infinitum. What can be done here to solve this problem?
Share
In general, calling the
setVisiblemethod is sufficient to make a Swing component to be shown or hidden.Just to be sure that it works, I tried the following:
The above program is able to affect the visibility by clicking on a
JButton.Could it be a Threading Issue?
My next suspicion was that perhaps a
Threadthat is not on the event dispatch thread (EDT) may not be affecting the display immediately, so I added the following after initializing theJLabelandJButton.With the new
Threadrunning, it changed the toggled the visibility of theJLabelevery 100 ms, and this also worked without a problem.Calling a Swing component off the event dispatch thread (EDT) is a bad thing, as Swing is not thread-safe. I was a little surprised it worked, and the fact that it works may just be a fluke.
Repaint the
JPanel?If the
JLabel‘s visibility is only being affected on resizing, it probably means that theJLabelis being drawn only when theJPanelis being repainted.One thing to try is to call the
JPanel‘srepaintmethod to see if the visibility of theJLabelwill change.But this method seems to be just a band-aid to a situation, if the main cause is due to a thread off the EDT is attempting to make changes to the GUI. (Just as a note, the
repaintmethod is thread-safe, so it can be called by off-EDT threads, but relying onrepaintis a workaround than a solution.)Try using
SwingUtilities.invokeLaterFinally, probably the thing I would try is the
SwingUtilities.invokeLatermethod, which can be called (and should only be called) from a thread running separate from the EDT, if it wants to affect the GUI.So, the earlier
Threadexample should be written as:If the change to the GUI is indeed occurring on a separate thread, then I would recommend reading Lesson: Concurrency in Swing from The Java Tutorials in order to find out more information on how to write well-behaving multi-threaded code using Swing.