Java – Difference between validate(), revalidate() and invalidate() in Swing GUI

javaswinguser interface

Swing components have multiple methods related to updates of screen layout, in particular:

The Java documentation defines these somewhat from a technical perspective, but it's not particularly clear how they are meant to be used.

What is the difference between these, and in what circumstances should you use one rather than the others?

Best Answer

validate() : In Swing when you create a Component, it is not valid i.e. its valid property is false. A component is said to be valid, when its width, height, location and stuff has been determined. This is usually done by calling their validate() method, directly or indirectly. When we call validate() on containers, it will validate the container (if it is invalid) by calling its doLayout() method, which typically will invoke the LayoutManager. Now each child placed on this container will be validated recursively, so that the entire tree will be laid out and will become valid.

revalidate() : revalidate() is to be called when you change an attribute that would affect their width/height and call repaint() when you change an attribute that would affect their appearance. For example, if your JFrame contains a JPanel, now at a certain point of time you removed that JPanel and inserted a new one in its place, depending on the contents of the newly placed JPanel, the size of the components inside the JPanel as well as The CONTAINER itself (by virtue of the layout manager used by it), changes. Which pushes it to the invalid state. So in order to validate this change, you have to explicitly call revalidate().

invalidate() : This is something I have never used, so there might not be much info I can provide about it. But it seems like the scenarios presented above can give a bit of a hint, as to what happens when using invalidate().