William William - 1 year ago 159
Java Question

Java Swing revalidate() vs repaint()

I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling

removeAll()
, then adding my new content, then calling
revalidate()
.

However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to
repaint()
in addition to
revalidate()
, it works as expected.

I'm sure on other occasions I've experienced that just calling
revalidate()
is enough.

So basically my question is - should I need to call both functions and if not, when should I call each of them?

Answer Source

You need to call repaint() and revalidate(). The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not cause the panel itself to do so (see this for the list of repaint triggers).

On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download