Finding an Applet's Size

When running inside a web browser the size of an applet is set by the height and width attributes and cannot be changed by the applet. Many applets need to know their own size. After all you don't want to draw outside the lines. :-)

Retrieving the applet size is straightforward with the getSize() method. java.applet.Applet inherits this method from java.awt.Component. getSize() returns a java.awt.Dimension object. A Dimension object has two public int fields, height and width. Below is a simple applet that prints its own dimensions.

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


public class SizeApplet extends Applet {

  public void paint(Graphics g) {

    Dimension appletSize = this.getSize();
    int appletHeight = appletSize.height;
    int appletWidth = appletSize.width;
    
    g.drawString("This applet is " + appletHeight + 
      " pixels high by " + appletWidth + " pixels wide.", 
      15, appletHeight/2);
    
  }

}

Size applet

Note how the applet's height is used to decide where to draw the text. You'll often want to use the applet's dimensions to determine how to place objects on the page. The applet's width wasn't used because it made more sense to left justify the text rather than center it. In other programs you'll have occasion to use the applet width too.


Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 18, 1997