The default layout manager for JDialog is flow layout. This manager adds controls from left to right, starting a new row each time it runs out of room. The main feature of flow layout is that it attempts to center align the components.
Here is a simple keypad created using the flow layout manager:
class KeyPadPanel extends JPanel {
JTextField display = new
JTextField("555-1234", 10);
JButton b1 = new
JButton("1");
JButton b2 = new
JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new
JButton("4");
JButton b5 = new
JButton("5");
JButton b6 = new
JButton("6");
JButton b7 = new
JButton("7");
JButton b8 = new
JButton("8");
JButton b9 = new
JButton("9");
JButton b0 = new
JButton("0");
JButton bSharp = new
JButton("#");
JButton bStar = new
JButton("*");
public KeyPadPanel() {
add(display);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(bSharp);
add(b0);
add(bStar);
}
}
public class KeyPad extends jutil.MainJFrame {
public KeyPad() {
setTitle("Key Pad");
Container contentPane =
getContentPane();
contentPane.add(new KeyPadPanel());
}
public static void main(String[] args)
{
JFrame demo = new KeyPad();
demo.show();
}
}
public KeyPadPanel() {
setLayout(new BorderLayout());
add(display, "North");
JPanel keys = new JPanel();
keys.setLayout(new GridLayout(4,
3));
keys.add(b1);
// etc.
add(keys, "South");
}
If we add keys without specifying the region, then it will be added to the central region and the east, west, and south regions disappear.
public KeyPadPanel() {
setLayout(new BorderLayout());
add(display, "North");
JPanel keys = new JPanel();
keys.setLayout(new GridLayout(4,
3));
keys.add(b1);
// etc.
add(keys);
}
public KeyPadPanel() {
setLayout(new BorderLayout());
JPanel p = new JPanel();
p.add(display);
add(p, "North");
JPanel keys = new JPanel();
keys.setLayout(new GridLayout(4,
3));
p = new JPanel();
p.add(b1);
keys.add(p);
p = new JPanel();
p.add(b2);
keys.add(p);
// etc.
add(keys);
}