Technical Support
Discussion Forum
Online Training
Read About Java
Java In-Depth
Product Discounts
Membership Information

Java Cup Logo

JDC Home Page


Top
Back
Next
Online Training
shadowSearchFAQFeedback

Canvas

A Canvas is a generic graphical component representing a region where you can draw things such as rectangles, circles, and text strings. For example, when writing a drawing applet, the region where objects are drawn would a subclass of Canvas.



Corresponding source code:

import java.applet.*;
import java.awt.*;
public class CanvasWidget extends Applet {
    public void init()
    {
        DrawingRegion region = new DrawingRegion(100,50);
        add(region);
    }
}

class DrawingRegion extends Canvas {
    int w,h;
    public DrawingRegion(int ww, int hh) {
        w=ww;
        h=hh;
        resize(w,h);
    }
    public void paint(Graphics g)
    {
        g.drawRect(0,0,w-1,h-1); // draw border
        g.drawString("A Canvas", 20,20);
    }
}

Method:

  • public void paint(Graphics g)
    You normally subclass Canvas to override the default Canvas paint method.

The normal event-convenience methods are also often overridden in Canvas subclasses such as mouseDown and mouseDrag.

Related exercise: