2008年11月27日星期四

Swing 的 Validate, Invalidate, Revalidate

Validate/Invalidate/Revalidate in Swing

Class Hierarchy

Component.invalidate():
Invalidates this component. This component and all parents above it are marked as needing to be laid out.





Component.validate()
Ensures that this component has a valid layout. This method is primarily intended to operate on instances of Container





Container.validate()
Validates this container and all of its subcomponents.
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
Set valid=true and call Container.validateTree().
Container.validateTree() will call all its sub containers’ validateTree() recursively, so all sub components’ Component.validate() method will be called.



Container.validateTree()





Container.invalidate()
Basically do the same thing as super class Component.invalidate except for notifying the layout manager the changes, since the major difference between Component and Container is that Container can contains objects with layout manager.
LayoutManager2.invalidate() will discard the cached size information about the layout, so next time the layout will be re-calculated.



Conclusion on validate/invalidate
Invalidate() causes the component hierarchy to be marked as needing to be laid out again, and the validate() causes that to be done. It may be expensive, but is a way of getting the peers to recalculate size and to do what is needed to bring the display up to date. It has limitations: it doesn't cause an immediate screen update when invoked from an event handler, where paintImmediately() does.

JComponent.revalidate()
Supports deferred automatic layout.
Calls invalidate and then adds this component's validateRoot to a list of components that need to be validated. Validation will occur after all currently pending events have been dispatched. In other words after this method is called, the first validateRoot (if any) found when walking up the containment hierarchy of this component will be validated. By default, JRootPane, JScrollPane, and JTextField return true from isValidateRoot.



Conclusion on revalidate
This method will automatically be called on this component when a property value changes such that size, location, or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke validate to get the contents of the GUI to update. Because RepaintManger.addInvalidComponent() will validate them.

没有评论: