|
|
Laying Out Components Within a Container |
Here's an applet that shows aGridLayoutin action.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.A
GridLayoutplaces 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 theGridLayoutwindow, you'll see that theGridLayoutchanges 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
GridLayoutand the components it manages. You can find the whole program inGridWindow.java. The program runs either within an applet (with the help ofAppletButton) or as an application.
The constructor tells theContainer contentPane = getContentPane(); contentPane.setLayout(new GridLayout(0,2)); 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"));GridLayoutclass to create an instance that has two columns and as many rows as necessary.The GridLayout API
TheGridLayoutclass has two constructors:At least one of thepublic GridLayout(int rows, int columns) public GridLayout(int rows, int columns, int horizontalGap, int verticalGap)rowsandcolumnsarguments must be nonzero. ThehorizontalGapandverticalGaparguments 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
The following table lists some of the examples that use grid layout.
Example Where Described Notes GridWindow.javaThis page Uses a 2-column grid. LabelDemo.javaHow to Use Labels Uses a 3-row grid. Converter.javaThe Anatomy of a Swing-Based Application Uses the 4-argument GridLayoutconstructor.
|
|
Laying Out Components Within a Container |