Using Components, the GUI Building Blocks |
The Canvas 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()
andpreferredSize()
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:
[Point to more Canvas subclass examples.]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); } }
Using Components, the GUI Building Blocks |