How to Use Layout Managers in Java
Understanding layout managers is the key to creating Swing frames in Java that are attractive and usable. So let’s take the mystery out of Swing layout so that you have complete control of where components are placed.
Six great Swing layout managers
Swing provides several layout managers for you to work with, including the following six:
Flow: This layout manager is the default for panels. It lays out components one after the other until it runs out of room; then it starts a new row of components.
Border: This layout manager is the default for frames. It divides the container into five regions: North, South, East, West, and Center. When you add a component, you can specify which region you want to place the component in.
Box: This layout manager arranges components in either a single row or a single column, depending on what alignment you specify when you create the layout manager.
Grid: This layout manager is ideal when you want to create a grid of identically sized components.
GridBag: This layout manager uses a more flexible grid than the Grid layout manager does. In GridBag layout, each row or column can be a different size; a component can span two or more rows or columns; and you can tell the layout manager what to do if the component is smaller or larger than the space allotted for it.
Group: This layout manager works best with a visual tool for designing user applications. In Group layout, you describe an arrangement from two points of view: left to right and top to bottom.
In addition to these six layout managers, Java provides a few others, including Card and Spring. The Card layout manager lets you create tabbed layouts, but it has been largely replaced by other components that do the same thing more effectively.
The Spring layout manager uses a weird concept called springs to let you position components. This layout manager isn’t intended to be hand-coded; instead, it’s designed to be used by code generators that create graphic user interface (GUI) code for you. Check here for more information on the Card and Spring layouts.
Applying layout managers
To set the layout manager for a panel or frame, you use the setLayout method. Here’s how you create a panel and set GridBag as its layout manager:
JPanel panel1 = new JPanel(); panel1.setLayout(new GridBagLayout());
If you want to use Flow layout with a panel or Border layout with a frame, you don’t have to do anything; those are the defaults.
In many cases, the best approach to creating complex frame layouts is using a combination of layout managers. You might create a panel with buttons that appear at the bottom of the frame. This panel would use Flow layout. Then you can add the panel to the South region of the frame, which uses Border layout by default.