Java Reference
In-Depth Information
Example 10•3: FlowLayoutPane.java (continued)
public class FlowLayoutPane extends JPanel {
public FlowLayoutPane() {
// Use a FlowLayout layout manager. Left justify rows.
// Leave 10 pixels of horizontal and vertical space between components.
this.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
// Add some buttons to demonstrate the layout.
String spaces = ""; // Used to make the buttons different
for(int i = 1; i <= 9; i++) {
this.add(new JButton("Button #" + i + spaces));
spaces += " ";
}
// Give ourselves a default size
this.setPreferredSize(new Dimension(500, 200));
}
}
GridLayout
GridLayout is a heavy-handed layout manager that arranges components left to
right and top to bottom in an evenly spaced grid of specified dimensions. When
you create a GridLayout , you can specify the number of rows and columns in the
grid, as well as the horizontal and vertical space the GridLayout should leave
between the components. Typically, you specify only the desired number of rows
or columns, leaving the other dimension set to 0 . This allows the GridLayout to
pick the appropriate number of rows or columns based on the number of compo-
nents. GridLayout does not honor the preferred sizes of its components. Instead, it
divides the size of the container into the specified number of equally sized rows
and columns and makes all the components the same size.
Example 10-4 shows a short program that arranges buttons in a grid using a Grid-
Layout layout manager. Figure 10-4 shows the resulting output.
Figure 10•4. Components laid out with a GridLayout
Search WWH ::




Custom Search