Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container

Doing Without a Layout Manager (Absolute Positioning)

Although it's possible to do without a layout manager, you should use a layout manager if at all possible. Layout managers make it easy to resize a container and adjust to platform-dependent component appearance and to different font sizes. They also can be reused easily by other containers and other programs. If your custom container won't be reused, can't be resized, and completely controls normally system-dependent factors such as font size and component appearance (implementing its own controls if necessary), then absolute positioning might make sense.

Here's an applet that brings up a window that uses absolute positioning.


Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:

Below are the instance variable declarations, constructor implementation, and paint() method implementation of the window class. Here's a link to the whole program. The program runs either within an applet, with the help of AppletButton, or as an application.

public class NoneWindow extends Frame {
    . . .
    private boolean laidOut = false;
    private Button b1, b2, b3;

    public NoneWindow() {
        super();
        setLayout(null);
        setFont(new Font("Helvetica", Font.PLAIN, 14));

        b1 = new Button("one");
        add(b1);
        b2 = new Button("two");
        add(b2);
        b3 = new Button("three");
        add(b3);
    }

    public void paint(Graphics g) {
        if (!laidOut) {
            Insets insets = insets();
            /* 
	     * We're guaranteed that insets() will return a valid Insets
             * if called from paint() -- it isn't valid when called from 
             * the constructor.
	     *
             * We could perhaps cache this in an ivar, but insets can
	     * change, and when they do, the AWT creates a whole new
	     * Insets object; the old one is invalid.
	     */
            b1.reshape(50 + insets.left, 5 + insets.top, 50, 20);
            b2.reshape(70 + insets.left, 35 + insets.top, 50, 20);
            b3.reshape(130 + insets.left, 15 + insets.top, 50, 30);

            laidOut = true;
        }
    }
    
    . . .
}


Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container