Using Layout Managers

 <  Day Day Up  >  

A layout manager is an object that implements the LayoutManager interface [2] and determines the size and position of the components within a container. [3] Although components can provide size and alignment hints, a container's layout manager has the final say.

[2] LayoutManager API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/LayoutManager.html.

[3] Way back in JDK 1.1 (an early release of the Java platform) a second interface, LayoutManager2 , was introduced. LayoutManager2 extends LayoutManager , providing support for maximum size and alignment. Many layout managers don't use those features, however.

This section discusses some of the common layout tasks :

  • Setting the layout manager

  • Adding components to a container

  • Providing size and alignment hints

  • Putting space between components

  • Setting the container's orientation

It ends with some tips on choosing a layout manager.

Setting the Layout Manager

As a rule, the only containers whose layout managers you need to worry about are JPanel s and content panes. Each JPanel object is initialized to use FlowLayout , unless you specify differently when creating it. Content panes use BorderLayout by default. If you don't like the default layout manager that a panel or content pane uses, you're free to change it to a different one.

You can set a panel's layout manager using the JPanel constructor. For example:

 JPanel panel = new JPanel(new BorderLayout()); 

After a container has been created, you can set its layout manager using the setLayout method. For example:

 Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout()); 

Although we recommend that you use layout managers, you can do without them. If you set a container's layout property to null, the container uses no layout manager. With this strategy, called absolute positioning , you must specify the size and position of every component within that container. One drawback of absolute positioning is that it doesn't adjust well when the top-level container is resized. It also doesn't adjust well to differences between users and systems, such as different font sizes and locales.

Adding Components to a Container

When you add components to a panel or content pane, the arguments you specify to the add method depend on the layout manager that the panel or content pane is using. For example, BorderLayout requires that you specify the area to which the component should be added using code like this:

 pane.add(aComponent, BorderLayout.PAGE_START); 

The how-to section for each layout manager has details on the arguments, if any, you need to specify to the add method. Some layout managers, such as GridBagLayout and SpringLayout , require elaborate setup procedures. Many, however, simply place components based on the order in which they were added to their container.

Except for JPanel s and content panes, Swing containers and content panes generally provide an API that you should use instead of the add method. For example, instead of adding a component directly to a scroll pane (actually to its viewport), you either specify it in the JScrollPane constructor or use setViewportView . Because of specialized API like this, you don't need to know which layout manager (if any) many Swing containers use. (For the curious , scroll panes happen to use ScrollPaneLayout .)

For information about adding components to a specific container, see the container's how-to section. You can find the how-to sections using A Visual Index to Swing Components (page 37) in Chapter 3.

Providing Size and Alignment Hints

Sometimes you need to customize the size hints a component provides to its container's layout manager so that the component will be laid out well. You do this by specifying one or more of the minimum, preferred, and maximum component sizes. You can invoke the component's methods for setting size hints ” setMinimumSize , setPreferredSize , and setMaximumSize . Or you can create a subclass of the component that overrides the appropriate getter methods ” getMinimumSize , getPreferredSize , and getMaximumSize . Here's an example of making a component's maximum size unlimited:

 component.setMaximumSize(new Dimension(Integer.MAX_VALUE,                                        Integer.MAX_VALUE)); 

Many layout managers don't pay attention to a component's requested maximum size; however, BoxLayout and SpringLayout do.

Besides size hints, you can also provide alignment hints ”for example, that the top edges of two components be aligned. You set alignment hints either by invoking the component's setAlignmentX and setAlignmentY methods or by overriding its getAlignmentX and getAlignmentY methods. Although most layout managers ignore alignment hints, Box- Layout honors them. You can find examples of setting the alignment in How to Use BoxLayout (page 462) in Chapter 8.

Putting Space between Components

Three factors influence the amount of space between visible components in a container:

The layout manager

Some layout managers automatically put space between components; others don't. Some also let you specify the amount of space between components. See the how-to section for each layout manager for information about spacing support.

Invisible components

You can create lightweight components that perform no painting but that can take up space in the GUI. Often you use invisible components in containers controlled by BoxLayout . See How to Use BoxLayout (page 462) in Chapter 8 for examples of using invisible components.

Empty borders

No matter which layout manager, you can affect the apparent amount of space between components by adding empty borders to them. The best candidates for empty borders are components that typically have no default border, such as panels and labels. Some other components might not work well with borders in some look-and-feel implementations because of the way their painting code is implemented. For information about borders, see How to Use Borders (page 535) in Chapter 9.

Setting the Container's Orientation

This book is written in English, with text that runs from left to right and then top to bottom. However, many other languages have different orientations, and the property component-Orientation provides a way of indicating that a particular component should use one of them (see Figure 8). In a component such as a radio button, the orientation might hint that the look and feel should switch the locations of the icon and the text in the button. In a container, it's a hint to the layout manager.

Figure 8. FlowLayoutDemo : (a) left-to-right orientation (default); (b) right-to-left orientation.

graphics/04fig08.gif

To set a container's orientation, you can use either the Component -defined setComponent-Orientation method or, to set the orientation on the container's children as well, the applyComponentOrientation method. The argument to either one can be a constant, such as ComponentOrientation.RIGHT_TO_LEFT , or it can be a call to the ComponentOrientation method getOrientation(Locale) . The following code causes all JComponent s to be initialized with an Arabic-language locale and then sets the orientation of the content pane and all components inside it accordingly :

 JComponent.setDefaultLocale(new Locale("ar")); JFrame frame = new JFrame(); ... Container contentPane = frame.getContentPane(); contentPane.applyComponentOrientation(                  ComponentOrientation.getOrientation(                            contentPane.getLocale())); 

The standard layout managers that support component orientation are FlowLayout , BorderLayout , BoxLayout , GridBagLayout , and GridLayout .

Choosing a Layout Manager

Layout managers have different strengths and weaknesses. This section discusses some common layout scenarios and which layout managers might work for each one. If none of the layout managers is right for your situation, feel free to use others that you write or find. Also keep in mind that flexible layout managers, such as GridBagLayout and SpringLayout , can fulfill many needs.

Scenario: You need to display a component in as much space as it can get.

If it's the only component in its container, use GridLayout or BorderLayout . Otherwise, BorderLayout or GridBagLayout might be a good match. If you use BorderLayout , you'll need to put the space-hungry component in the center. With GridBagLayout , you'll need to set the constraints for the component fill=GridBagConstraints.BOTH . Another possibility is to use BoxLayout and have the component specify very large preferred and maximum sizes.

Scenario: You need to display a few components in a compact row at their natural size.

Consider using a JPanel to group the components and using either JPanel 's default FlowLayout manager or the BoxLayout manager. SpringLayout is also good for this.

Scenario: You need to display a few components of the same size in rows and columns .

GridLayout is perfect for this.

Scenario: You need to display a few components in a row or column, possibly with varying amounts of space between them, custom alignment, or custom component sizes.

BoxLayout is perfect for this.

Scenario: You need to display aligned columns, as in a form-like interface where a column of labels is used to describe text fields in an adjacent column.

SpringLayout is a natural choice for this. The SpringUtilities class used by several of our examples defines a makeCompactGrid method that lets you easily align multiple rows and columns of components.

Scenario: You have a complex layout with many components.

Consider either a very flexible layout manager, such as GridBagLayout or Spring- Layout , or grouping the components into one or more JPanel s to simplify layout. If you take the latter approach, each JPanel might use a different type of layout manager.

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net