Manually Controlling Layout

Java applets are containers, and can thus contain any number of components, which can themselves be containers. A layout manager can automate placement of components within a container, so that the applet can adapt itself to the size of the window it receives from the browser.

An applet can position and resize components itself:
It first calls setLayout(null) to disable automatic positioning of components. It adds components and calls their reshape() (JDK 1.0.2) or setBounds() (JDK 1.1) method to position and resize them.

The following example shows an applet that moves a button each time you click on it.


Below is the source code for this example (minus import statements):
public class ButtonApplet extends Applet {
    Button move;
    Random r;

    public void init() {
	setLayout(null);
        move = new Button("Move me");
        add(move);
	move.reshape(0,0,70,30);
        r = new Random();
    }

    public boolean action(Event evt, Object whatAction) {
        if (!(evt.target instanceof Button))
            return false;
        String buttonLabel = (String)whatAction;
        if (buttonLabel == "Move me") {
            move.reshape(Math.abs(r.nextInt())%(size().width-70),
                Math.abs(r.nextInt())%(size().height-30),70,30);
            repaint();
        }
        return true;
    }
}