The java.awt.Canvas class is a rectangular area on which you can draw using the methods of java.awt.Graphics discussed last week. The Canvas class has only three methods:

  public Canvas()
  public void addNotify()
  public void paint(Graphics g)

You generally won't instantiate a canvas directly. Instead you'll subclass it and override the paint() method in your subclass to draw the picture you want.

For example the following Canvas draws a big red oval you can add to your applet.

import java.awt.*;

public class RedOval extends Canvas {

  public void paint(Graphics g) {
    Dimension d = this.getSize();
    g.fillOval(0, 0, d.width, d.height);
  public Dimension getMinimumSize() {
    return new Dimension(50, 100);  

  public Dimension getPreferredSize() {
    return new Dimension(150, 300);  

  public Dimension getMaximumSize() {
    return new Dimension(200, 400);  


Any applet that uses components should not also override paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create a Canvas object and do your drawing in its paint() method.

Custom canvases are added to applets just like any other component. For example,

  public void init() {
    this.add(new RedOval());

Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2001, 2003 Elliotte Rusty Harold
Last Modified April 8, 2003