GridLayout
GridLayout arranges
components into regularly spaced rows and columns. The components are
arbitrarily resized to fit the grid; their minimum and preferred sizes are
consequently ignored. GridLayout is
most useful for arranging identically sized objects—perhaps a set of JPanels, each using a different layout
manager.
GridLayout takes the number of
rows and columns in its constructor. If you subsequently give it too many
objects to manage, it adds extra columns to make the objects fit. You can
also set the number of rows or columns to 0, which means that you don’t care how many
elements the layout manager packs in that dimension. For example, GridLayout(2,0) requests a layout with two rows
and an unlimited number of columns; if you put 10 components into this
layout, you’ll get 2 rows of 5 columns each.[42]
The following example sets a GridLayout with three rows and two columns as
its layout manager:
//file: Grid.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassGridextendsJPanel{publicGrid(){setLayout(newGridLayout(3,2));add(newJButton("One"));add(newJButton("Two"));add(newJButton("Three"));add(newJButton("Four"));add(newJButton("Five"));}publicstaticvoidmain(String[]args){JFrameframe=newJFrame("Grid");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(200,200);frame.setLocation(200,200);frame.setContentPane(newGrid());frame.setVisible(true);}}
The results are shown in Figure 19-3 ...