Herong's Tutorial Notes on Swing
Dr. Herong Yang, Version 3.05, 2006

Layouts of Components

Part:   1   2  3  4 

This chapter discusses:

  • What is a layout?
  • BorderLayout
  • FlowLayout
  • BoxLayout
  • GridLayout
  • GridBagLayout

What Is a Layout?

Layout is a set of rules that defines how graphical components should be positioned in in a container.

There two ways to position a component is a container:

  • Using a predefined layout and allowing the layout to decide where to position the component. This is a soft way of positioning a component. If the container changes its size, the component's position will be adjusted. But you may not able to get precisely where you want to component to be.
  • Specifying the position of the component using the container's coordinates. This is a hard way of positioning a component. You can get precisely where you want the component to be. But if the container changes its size, the component's position will not be adjusted.

AWT offers a number of predefined layouts for you to use. I will show you some of the basic ones in this chapter

BorderLayout

java.awt.BorderLayout - A very simple layout that:

  • Divides the container into five regions: east, south, west, north, and center.
  • Takes maximum 5 components only, one per region.
  • Resizes each component to match the size of its region.
  • Acts as the default layout in a container.
  • Resizes each region when the container is resized.

I really don't see any potential of using this layout in any real applications. Do you?

FlowLayout

java.awt.FlowLayout - Another very simple layout that:

  • Takes unlimited number of components.
  • Uses the default size of each component.
  • Positions each component next to each other in a row. If there is not enough room in the current row, the component will be positioned at the beginning of the next row.
  • Re-arranges the flow when the container is resized.

I don't see any potential use of this layout either. But I am interested to see how it re-arranges the flow when the container is resized. So I decided to use FlowLayout to position a window of several different types of components. I wanted the window to look like this:

- Details ----------------
|     Name: Text         |
|   System: Radio button |
| Language: Check box    |
|     Year: Dropdown     |
--------------------------
        OK  Cancel

(Continued on next part...)

Part:   1   2  3  4 

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Swing - Layouts of Components