Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks


How to Use Canvases

The Canvas (in the API reference documentation) class exists to be subclassed. It does nothing on its own; it merely provides a way for you to implement a custom Component. For example, Canvases are useful as display areas for images and custom graphics, whether or not you wish to handle events that occur within the display area.

Canvases are also useful when you want a control -- a button, for example -- that doesn't look like the the default implementation of the control. Since you can't change a standard control's appearance by subclassing its corresponding Component (Button, for example), you must instead implement a Canvas subclass to have both the look you want and the same behavior as the default implementation of the control.

When implementing a Canvas subclass. take care to implement the minimumSize() and preferredSize() methods to properly reflect your canvas's size. Otherwise, depending on the layout your canvas's container uses, your canvas could end up too small -- perhaps even invisible.

Here's an example of a Canvas subclass that displays an image:

class ImageCanvas extends Canvas {
    ImageCanvas(Image img, Dimension prefSize) {
        image = img;
        preferredSize = prefSize;
    }
 
    public Dimension minimumSize() {
        return preferredSize;
    }

    public Dimension preferredSize() {
        return preferredSize;
    }

    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, this);
    }
}
[Point to more Canvas subclass examples.]


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks