This chapter tells us how to position the onscreen representations of the Components.
It will show us how to use a layout managers the AWT provides. It will also show how to
write our own layout manager. It will even tell how to do without a layout manager and use
the absolute positions. Finally, it will discuss some of the common layout problems
and solutions.
General Rules to Use the Layout Managers
Unless we explicitly tell a Container not to use the layout manager, it will be
associated with its own instance of a layout manager. This layout manager is been
automatically consulted every time the Container needs to change its appearance.
Most of the layout managers do not require programs to directly call layout manager's
methods.
How to Choose a Layout Manager
AWT-provided layout managers have different strengths and weakness. This section
discusses some of the common layout scenarios and which AWT layout managers may work
for each scenario. If none of the AWT layout managers is right for our situation, we
should use layout managers contributed to the net.
Scenario: We need to display a component in as much space as it can.
Consider using the BorderLayout or GridBagLayout. If you use the BorderLayout, we
will need to put the space-hungry component at the center. With GridBagLayout, we will
need to set constraints for the component so that the fill=GridBagConstraints.BOTH. Or,
if we do not mind every other component in the same container being as large as our
space-hungry component, we can use a GridLayout.
Scenario: We need to display a few components in the compact row at their natural size.
Consider using Panel to hold the components and using a Panel's default FlowLayout
manager.
Scenario: We need to display few same-sized components in rows and/or the columns.
GridLayout is perfect for this purpose. Use the Panel if it isnecessary to contain the
components.
How to Create a Layout Manager and Associate with a Container
Every container has the default layout manager associated with it. All Panels
(including an Applets) are initialized to use the FlowLayout. All Windows
(except the special-purpose ones like FileDialog) are initialized to use the BorderLayout.
If we want to use a Container's default layout manager, we don't have to do anything.
The constructor for each of the Container creates the layout manager instance and
initializes a Container to use it.
To use the non-default layout manager, we need to create instance of the desired
layout manager class and tell the Container to use it. Below is a code that
does this. This code creates the CardLayout manager and sets it as the layout manager
for the Container.
aContainer.setLayout(new CardLayout());
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.