Whenever I remove and add swing components from say JPanel, shall I perform call on validate or revalidate?
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.
In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(), paintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint(). repaint(): This method cannot be overridden. It controls the update() -> paint() cycle.
revalidate(): This method tells the layout manager to recalculate the layout that is necessary when adding components.
revalidate() would be better. revalidate() marks all the container upto the top level as not proper or not valid. Then it calls validate() on the top level. The validate() method of the parent checks if at least one of its immediate children is signaled invalid or improper. it calls validate of the parent. so calling revalidate() automatically means calling validate().
revalidate()
is basically a invalidate()
followed by a validate()
.
Look at Sun's Java source code.
You want to call revalidate()
.
At least in Java 7, revalidate()
doesn't necessarily "erase" removed components from the screen. I believe that happens when the bounding box shrinks. For these cases, call repaint()
after the revalidate()
.
I would think revalidate() is what you want. The validate() method will be automatically called for you after a call to revalidate(). See the Java API for JComponent.revalidate().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With