How to Manually Position Components

If none of those things convince you that you really shouldn't use absolute positioning, I'll let you in on the secret: pass null to setLayout(), that is call

setLayout(null);

Then move and resize each of your components to their desired locations and sizes in the paint() method using setLocation() and setSize():

public void setLocation(int x, int y)
public void setSize(int width, int height)

where x and y are the coordinates of the upper left hand corner of the bounding box of your component and width and height are the width and height in pixels of the bounding box of your component.

This applet puts a button precisely 30 pixels wide by 40 pixels high at the point (25, 50):

Applet with one big button

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

public class ManualLayout extends Applet {

  private boolean laidOut = false;
  private Button  myButton;

  public void init() {
    this.setLayout(null);
    this.myButton = new Button("OK");
    this.add(this.myButton);
  }

   public void paint(Graphics g) {
     if (!this.laidOut) {
        this.myButton.setLocation(25, 50);
        this.myButton.setSize(30, 40);
        this.laidOut = true;
     }
   }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 1, 2002