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 that puts a button precisely 30 pixels wide by 40 pixels high at the point (25, 50):

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
Last Modified April 16, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu