Page 730 - Introduction to Programming with Java: A Problem Solving Approach
P. 730
696 Chapter 17 GUI Programming—Component Layout, Additional GUI Components
Layout Manager
Description
BorderLayout
Splits container into five regions—north, south, east, west, and center. Allows one component per region.
BoxLayout
Allows components to be arranged in either a single column or a single row.
FlowLayout
Allows components to be added left to right, flowing to next row as necessary.
GridLayout
Splits container into a rectangular grid of equal-sized cells. Allows one component per grid cell.
GridBagLayout
A more flexible and complex version of GridLayout. Allows grid cells to vary in size.
Figure 17.2 Several of the more popular layout managers
In the previous chapter, we used the simplest type of layout manager—the FlowLayout manager. The FlowLayout manager is useful for some situations, but we’ll often need alternative layout managers for other situations. In this chapter, we’ll describe the FlowLayout manager in more detail, and we’ll also describe the BorderLayout and GridLayout managers. Those are the three most popular layout man- agers, so you should know them well.
Assigning a Layout Manager
Apago PDF Enhancer
To assign a particular layout manager to a JFrame window from within a class that extends JFrame, call the setLayout method as follows:
setLayout(new <layout-manager-class>());
In this code template, replace <layout-manager-class> by one of the layout manager classes (e.g., FlowLayout, BorderLayout, GridLayout). If setLayout is not called, then the BorderLayout manager is used, because that’s the default layout manager for a JFrame window.
Layout manager classes are in the java.awt package, so that package must be imported. Of course, if you’ve already imported it for something else, then there’s no need to import it again.
17.3 FlowLayout Manager
In the previous chapter, we wanted to present GUI basics without getting bogged down in layout manager details. So we chose a simple layout manger, FlowLayout, that didn’t require much explanation. We just used it and didn’t dwell on particulars. Now it’s time to explain the particulars, so you can take advantage of its functionality more fully.
Layout Mechanism
The FlowLayout class implements a simple one-compartment layout scheme that allows multiple compo- nents to be inserted into the compartment. When a component is added to the compartment, it is placed to the right of any components that were previously added to the compartment. If there is not enough room to add a component to the right of the previously added components, the new component is placed on the next line (i.e., it “flows” to the next line). Note the following example.