Nested Panels

Even simple graphical interfaces often require more than one layout manager. That is, portions of the visible applet region need be laid out differently than other portions. Further, you may want to create compound components such as a LabeledTextField that contains both a Label and a TextField. This section describes how multiple components may be combined into a single Container and treated like an ordinary Component for layout and encapsulation purposes.

How would you build a telephone key pad object? You could easily set the applet layout manager to GridLayout and then add the keys, however, your whole applet would be a keypad. If you needed the key pad as only a portion of the applet, this simple approach would not work. The solution is to place all of the keys in their own Container--that way you can treat the whole key pad like a single Component. Class Panel is normally used to produce compound Component objects as we have done in the following KeyPad class:

class KeyPad extends Panel {
    String[] keys = { "1","2","3",
                      "4","5","6",
                      "7","8","9",
                      "*","0","#" };
    Button[] b = new Button[keys.length];
    public KeyPad() {
        setLayout(new GridLayout(4,3));
        for (int i=0; i<keys.length; i++) {
            b[i] = new Button(String.valueOf(keys[i]));
            add(b[i]);
        }
    }
}

An applet can then instance and display KeyPad objects easily:



Corresponding source code:

import java.awt.*;
import java.applet.Applet;

public class NestedTest extends Applet {
    public void init() {
        KeyPad k1 = new KeyPad();
        KeyPad k2 = new KeyPad();
        add(k1);
        add(k2);
    }
}

The containment hierarchy diagram for NestedTest reflects the fact that the main applet contains only two elements--KeyPad containers, which in turn contain 12 keys each:

What if I want the key pad to be bigger? The applet's default FlowLayout manager uses the preferred size of each Component when laying them out. The preferred size of the KeyPad will be the combined preferred size of the keys because the KeyPad size is not specified and FlowLayout does not try to stretch its components. To make a bigger key pad, you must set the preferred size of the Keypad Container, which the applet FlowLayout will use to set the size of the KeyPad. Define preferredSize in class KeyPad to return 100x100 so that the applet will stretch the keypad to 100x100 pixels:

public Dimension preferredSize() {
    return new Dimension(100,100);
}

The applet then looks like:



It is normally not a good idea to specify the size of components because different systems have different font and widget sizes, but this example demonstrates how nested containers are used.

Related Magercise(s):

This section has the following subsections: