Before we go on to discussing individual Swing components, such as text fields and radio buttons, we need to briefly cover how to arrange these components inside a frame. Since the Java SDK has no form designer like those in Visual Basic or Delphi, you need to write code to position (lay out) the user interface components where you want them to be. Of course, if you have a Java-enabled development environment, it will probably have a layout tool that automates some or all of these tasks. Nevertheless, it is important to know exactly what goes on "under the hood" since even the best of these tools will usually require hand-tweaking to get a professional look and feel. Let's start by reviewing the program from the last chapter that used buttons to change the background color of a frame (see ).

A panel with three buttons

Java graphics 09fig05

Let us quickly recall how we built this program:

  1. We defined the look of each button by setting the label string in the constructor, for example:
    JButton yellowButton = new JButton("Yellow")
    
  2. We then added the individual buttons to a panel, for example, with:
    add(yellowButton);
    
  3. Then, we added the needed event handlers, for example:
    yellowButton.addActionListener(listener);
    

What happens if we add more buttons? shows what happens when you add six buttons to the panel. As you can see, they are centered in a row, and when there isn't any more room, a new row is started.

A panel with six buttons managed by a flow layout

Java graphics 09fig06

Moreover, the buttons stay centered in the panel, even when the user resizes the frame (see ).

Changing the panel size rearranges the buttons automatically

Java graphics 09fig07

Java has a very elegant concept to enable this dynamic layout: all components in a container are managed by a layout manager. In our example, the buttons are managed by the flow layout manager, the default layout manager for a panel. The flow layout manager lines the components horizontally until there is no more room and then starts a new row of components. When the user resizes the container, the layout manager automatically reflows the components to fill the available space. You can choose how you want to arrange the components in each row. The default is to center them in the container. The other choices are to align them to the left or to the right of the container. To use one of these alignments, specify LEFT or RIGHT in the constructor of the FlowLayout object.

setLayout(new FlowLayout(FlowLayout.LEFT));

Java graphics notes_icon

Normally, you just let the flow layout manager control the vertical and horizontal gaps between the components. You can, however, force a specific horizontal or vertical gap by using another version of the flow layout constructor. (See the API notes.)

java.awt.Container 1.0

Java graphics api_icon

java.awt.FlowLayout 1.0

Java graphics api_icon