After you add (or remove) Components to/from a Container, you must do a Container.validate() to let the components jostle about (i.e. let the LayoutManager determine their new sizes and positions). This does not happen automatically, to avoid recalculating the layout after every add in a continuous stream of adds. It would just cause annoying flicker.
In contrast pack does a validate after computing the size for a frame or window based on the preferred sizes of all the contained components. So pack tends to shrink the layout where validate leaves it the same size but rearranges the contents.
Most often you call validate or pack after a frame or other container been composed, just before the Frame.setVisible( true ). validate is also called as the second step in processing a COMPONENT_RESIZED event. Invoking invalidate by itself will not schedule a validate. Invoking validate by itself will not schedule a repaint. repaint does not automatically schedule a validate before the paint. If your recent layout changes (e.g. button adding/removing) are not showing up, make sure you do a validate prior to any repaint.
Note that you can validate an invisible container, (containing visible children) and it will leave room for all the components inside it. However, if one of the components inside it, itself, is currently invisible, then the layout manager will typically not leave room for it.
Even though validate does nothing if the layout is already valid, don’t call validate unnecessarily. Wait until just before the setVisible or repaint to avoid the overhead of calculating the entire layout just to deal with some tiny change.
While you are composing a Frame you usually would temporarily setVisible( false ), waiting until all the components are added, before allowing any validate/ repaints to be triggered, then validate() then setVisible( true ) when you were ready for your masterwork to be revealed. Traditionally you do the setVisible( false ) in the constructor and the validate() and setVisible( true ) in the code that calls the constructor.
This page is posted
Optional Replicator mirror
|no blog for this page||Canadian
Your face IP:[220.127.116.11]
You are visitor number|