Using Layout Managers

In Java, the placement of components within a container depends on the size of other components and the height and width of the container. The layout of buttons, text fields, and other components can be affected by the following things:

  • The size of the container
  • The size of other components and containers
  • The layout manager that is being used

There are several layout managers you can use to affect how components are shown. The default manager for panels is the FlowLayout class in the java.awt package, which was used during the previous hour. Under FlowLayout, components are dropped onto an area in the same way words are organized on a printed page in English—from left to right, then on to the next line when there's no more space. To set up a container to work under FlowLayout, set up the container's layout manager by calling the Container object's setLayout() method with the FlowLayout object as an argument.The following example could be used in a frame so that it will employ flow layout when components are added:

FlowLayout topLayout = new FlowLayout();
setLayout(topLayout);


You also can set up a layout manager to work within a specific container, such as a JPanel object. You can do this by using the setLayout() method of that container object. The following statements create a JPanel object called inputArea and set it up to use FlowLayout as its layout manager:

JPanel inputArea = new JPanel();
FlowLayout inputLayout = new FlowLayout();
inputArea.setLayout(inputLayout);


To give you an idea of how the different layout managers work, a simple app will be shown under each of the classes. The Crisis app has a graphical user interface with five buttons. Load your word processor and open up a new file called Crisis.java. Enter Listing 14.1 and save the file when you're done.

Listing 14.1. The Full Text of Crisis.java
 1: import java.awt.*;
 2: import javax.swing.*;
 3:
 4: public class Crisis extends JFrame {
 5: JButton panicButton = new JButton("Panic");
 6: JButton dontPanicButton = new JButton("Don't Panic");
 7: JButton blameButton = new JButton("Blame Others");
 8: JButton mediaButton = new JButton("Notify the Media");
 9: JButton saveButton = new JButton("Save Yourself");
10:
11: public Crisis() {
12: super("Crisis");
13: setSize(308, 128);
14: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15: FlowLayout flo = new FlowLayout();
16: setLayout(flo);
17: add(panicButton);
18: add(dontPanicButton);
19: add(blameButton);
20: add(mediaButton);
21: add(saveButton);
22: setVisible(true);
23: }
24:
25: public static void main(String[] arguments) {
26: Crisis cr = new Crisis();
27: }
28: }


After compiling the Crisis app, you can run it with the following command:

java Crisis


Screenshot shows the app running.

Screenshot Arranging components using flow layout.

Java ScreenShot


The FlowLayout class uses the dimensions of its container as the only guideline for how to lay out components. Resize the window of the app to see how components are instantly rearranged. Make the window twice as wide, and you'll see all of the JButton components are now shown on the same line. Java programs often will behave differently when their display area is resized.

The GridLayout Manager

The GridLayout class in the java.awt package organizes all components in a container into a specific number of rows and columns. All components are allocated the same amount of size in the display area, so if you specify a grid that is three columns wide and three rows tall, the container will be divided into nine areas of equal size. The following statements create a container and set it to use a grid layout that is two rows wide and three columns tall:

GridLayout grid = new GridLayout(2, 3);
setLayout(grid);


Screenshot shows what the Crisis app would look like if it used grid layout.

Screenshot Arranging components using grid layout.

Java ScreenShot


Some of the labels in Screenshot display text that has been shortened—if the text is wider than the area available in the component, the label will be shortened using ellipses (…). GridLayout places all components as they are added into a place on a grid. Components are added from left to right until a row is full and then the leftmost column of the next grid is filled.

The BorderLayout Manager

The next layout manager to experiment with is the BorderLayout class, also in java.awt. The following statements create a container that uses border layout, placing components at specific locations within the layout:

BorderLayout crisisLayout = new BorderLayout();
setLayout(crisisLayout);
add(panicButton, BorderLayout.NORTH);
add(dontPanicButton, BorderLayout.SOUTH);
add(blameButton, BorderLayout.EAST);
add(mediaButton, BorderLayout.WEST);
add(saveButton, BorderLayout.CENTER);


Screenshot shows how this looks in the Crisis app.

Screenshot Arranging components using border layout.

Java ScreenShot


The BorderLayout manager arranges components into five areas: four denoted by compass directions and one for the center area. When you add a component under this layout, the add() method includes a second argument to specify where the component should be placed. This argument should be one of five class variables of the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER are used for this argument. Like the GridLayout class, BorderLayout devotes all available space to the components. The component placed in the center is given all the space that isn't needed for the four border components, so it's usually the largest.

The BoxLayout Manager

Another handy layout manager, BoxLayout, makes it possible to stack components in a single row horizontally or vertically. Unlike the other layout managers described during this hour, the BoxLayout class is in the javax.swing package. When components are lined up in FlowLayout, they hit the right margin and wrap around to the next line, just like the words in this paragraph. For the times when you want components on a single left-to-right or top-to-bottom line, they can be placed in a panel arranged with BoxLayout. Create the panel, then create a layout manager with two arguments:

  • The component to organize in box layout
  • The value BoxLayout.Y_AXIS for vertical alignment and BoxLayout.X_AXIS for horizontal alignment

Here's code to stack the Crisis components:

JPanel pane = new JPanel();
BoxLayout box = new BoxLayout(pane, BoxLayout.Y_AXIS);
pane.setLayout(box);
pane.add(panicButton);
pane.add(dontPanicButton);
pane.add(blameButton);
pane.add(mediaButton);
pane.add(saveButton);
add(pane);


Screenshot shows how this turns out.

Screenshot Stacking components using box layout.

Java ScreenShot


Separating Components with Insets

As you are arranging components within a container, you might want to move components away from the edges of the container. This is accomplished using Insets, an object that represents the border area of a container. The Insets class, which is part of the java.awt package, has a constructor method that takes four arguments: the space to leave at the top, left, bottom, and right on the container. Each argument is specified using pixels, the same unit of measure employed when defining the size of a frame. The following statement creates an Insets object:

Insets around = new Insets(10, 6, 10, 3);


The around object represents a container border that is 10 pixels inside the top edge, 6 pixels inside the left, 10 pixels inside the bottom, and 3 pixels inside the right. To make use of an Insets object in a container, you must override the container's getInsets() method. This method has no arguments and returns an Insets object, as in the following example:

public Insets getInsets() {
 Insets squeeze = new Insets(50, 15, 10, 15);
 return squeeze;
}


Screenshot shows how this would change one of the preceding examples, the BorderLayout-managed interface shown in Screenshot.

Screenshot Using insets to add space around components.

Java ScreenShot


The container shown in Screenshot has an empty border that's 15 pixels from the left edge, 10 pixels from the bottom edge, 15 pixels from the right edge, and 50 pixels from the top edge.

By the Way

A JFrame container has a built-in inset to make room for the frame's title bar. When you override getInsets() and set your own values, a low inset value will cause the container to display components underneath the title bar.


      
Comments