Java Reference
In-Depth Information
A GridLayout layout manager can be constructed in two ways:
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap);
// rows, columns: number of rows and columns in the grid
// hgap, vgap: horizontal/vertical gap between the components
Note that when you specify 0 (zero) for the number of rows or columns (but not both), any number
of components can be placed in the column or row, respectively (the actual nonā€zero value is then
effectively ignored). When you specify both the number of rows and columns, the column value is
also ignored. The number of components you add and the number of rows you have specified deter-
mine the real number of columns.
The following Try It Out shows an example.
Creating the Useless pocket Calculator
try it out
In this Try It Out, you create a JFrame to see how the GridLayout layout manager works. You also see
how containers can be nested to create more complex layouts.
1.
As always, feel free to create a new project in Eclipse when you want to. Create a class called
GridLayoutFrame with the following content:
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridLayoutFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GridLayout frame");
// 7 8 9 0
// 4 5 6 C
// 1 2 3 =
// + - * /
frame.getContentPane().setLayout(new GridLayout(4, 4));
addButtons(frame.getContentPane(),
"7", "8", "9", "0", "4", "5", "6", "C",
"1", "2", "3", "=", "+", "-", "*", "/"
);
frame.pack();
frame.setVisible(true);
}
Search WWH ::




Custom Search