3.6. Container

Container is a Control that can contain other Controls, thus forming a hierarchy of components. Container enables components to add, remove and retrieve other controls. Listed below are example Containers:

These Containers are depicted in the figure below.

Container Class Diagram

Figure 3.4. Container Class Diagram


The following classes provides convenient extension points for creating custom Containers:

Lets cover each of them here.

3.6.1. AbstractContainer

Enables easy creation of custom Containers, for example an html div or span element:

public class Div extends AbstractContainer {

    public Div(String name) {
        super(name);
    }

    public String getTag() {
        // Return the control's HTML tag.
        return "div";
    }
}

Lets try out the newly created Container above: (note the MockContext used in this test is described in the Mock Test Support documentation)

public class Test {
    public static void main (String args[]) {
        // Create mock context in which to test the container.
        MockContext.initContext();

        // Create a div instance called "mydiv"
        String containerName = "mydiv";
        Div mydiv = new Div(containerName);

        // Add a control to the container
        mydiv.add(new TextField("myfield"));

        System.out.println(mydiv);
    }
}

Executing the above example results in the following output:

<div name="mydiv" id="mydiv">
    <input type="text" name="myfield" id="myfield" value="" size="20" />
</div>

3.6.2. AbstractContainerField

AbstractContainerField extends Field and implements the Container interface. This provides a convenient base class in case you run into a situation where you need both a Field and Container.

Below is an example of how AbstractContainerField might be used:

public class FieldAndContainer extends AbstractContainerField {

    public FieldAndContainer(String name) {
        super(name);
    }

    // Return the html tag to render
    public String getTag() {
        return "div";
    }
}

To test the new class we use the following snippet:

public class Test {
    public static void main (String args[]) {
        // Create mock context in which to test the container.
        MockContext.initContext();

        // Create a FieldContainer instance called "field_container"
        String containerName = "field_container";
        FieldAndContainer fieldAndContainer = new FieldAndContainer(containerName);

        // Add a couple of fields to the container
        fieldAndContainer.add(new TextField("myfield"));
        fieldAndContainer.add(new TextArea("myarea"));

        System.out.println(fieldAndContainer);
    }
}

Executing the snippet produces the output:

<div name="field_container" id="field_container">
    <input type="text" name="myfield" id="myfield" value="" size="20"/>
    <textarea name="myarea" id="myarea" rows="3" cols="20"></textarea>
</div>