Previous | Next | Trail Map | Creating a User Interface (with Swing) | 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 as well as 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:


Note: Because the preceding applet runs using Java Plug-in 1.1.1, it is a Swing 1.0.3 version of the applet. To run the Swing 1.1 Beta 3 version of the applet, you can use the JDK Applet Viewer to view None.html, specifying swing.jar in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.

Below are the instance variable declarations and constructor 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 JFrame {
    . . .
    private boolean laidOut = false;
    private JButton b1, b2, b3;

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

        b1 = new JButton("one");
        contentPane.add(b1);
        b2 = new JButton("two");
        contentPane.add(b2);
        b3 = new JButton("three");
        contentPane.add(b3);

        Insets insets = contentPane.getInsets();
        b1.setBounds(25 + insets.left, 5 + insets.top, 75, 20);
        b2.setBounds(55 + insets.left, 35 + insets.top, 75, 20);
        b3.setBounds(150 + insets.left, 15 + insets.top, 75, 30);

        setContentPane(contentPane);

        . . .
    }

    . . .
}


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