Difference between validate(), revalidate() and invalidate() in Swing GUI
invalidate()
marks the container as invalid. Means the content is somehow wrong and must be re-laid out. But it's just a kind of mark/flag. It's possible that multiple invalid containers must be refreshed later.
validate()
performs relayout. It means invalid content is asked for all the sizes and all the subcomponents' sizes are set to proper values by LayoutManager.
revalidate()
is just sum of both. It marks the container as invalid and performs layout of the container.
UPDATE:
Some code from Component.java
public void revalidate() {
revalidateSynchronously();
}
/**
* Revalidates the component synchronously.
*/
final void revalidateSynchronously() {
synchronized (getTreeLock()) {
invalidate();
Container root = getContainer();
if (root == null) {
// There's no parents. Just validate itself.
validate();
} else {
while (!root.isValidateRoot()) {
if (root.getContainer() == null) {
// If there's no validate roots, we'll validate the
// topmost container
break;
}
root = root.getContainer();
}
root.validate();
}
}
}
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()
.