Laying Out Components within a Container |
Here's an applet that shows aGridLayout
in action.
Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:
Note: Because the preceding applet runs using Java Plug-in 1.1.1, it is a Swing 1.0.3 version of the applet. To run the Swing 1.1 Beta 3 version of the applet, you can use the JDK Applet Viewer to viewGrid.html
, specifyingswing.jar
in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.A
GridLayout
places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize theGridLayout
window, you'll see that theGridLayout
changes the cell size so that the cells are as large as possible, given the space available to the container.Below is the code that creates the
GridLayout
and the components it manages. (Here's the whole program. The program runs either within an applet, with the help ofAppletButton
, or as an application.)
The constructor tells the//Construct a GridLayout with 2 columns and an unspecified number of rows. JPanel contentPane = new JPanel(); contentPane.setLayout(new GridLayout(0,2)); contentPane.setFont(new Font("SansSerif", Font.PLAIN, 14)); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5")); setContentPane(contentPane);GridLayout
class to create an instance that has two columns and as many rows as necessary. It's one of two constructors forGridLayout
. Here are both constructors:At least one of thepublic GridLayout(int rows, int columns) public GridLayout(int rows, int columns, int horizontalGap, int verticalGap)rows
andcolumns
arguments must be nonzero. ThehorizontalGap
andverticalGap
arguments to the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero. In the applet above, any apparent gaps are the result of the buttons reserving extra space around their apparent display area.Examples that Use GridLayout
[PENDING]
Laying Out Components within a Container |