Java AWT Canvas Freelance Drawing

Canvas, in general sense, is a cloth where a painter can put some painting. But for us, Canvas is a class from java.awt package on which a programmer can draw some shapes or display images. A mouse click or a keyboard key press on the canvas can generate events and these events can be converted into meaningful drawings; for example, a mouse click can be converted into an oval and multiple fill ovals drawn side-by-side makes a line. Programmer ties (adds) the canvas to a frame or applet.

Two programs are given on Java AWT Canvas Freelance Drawing.

In the second program, canvas is drawn using Graphics object and not using conventional paint() method.

Following is the class signature

public class Canvas extends Component implements Accessible

Drawing Oval on Canvas

In the following simple canvas code, a canvas is created and a oval is drawn on it.

import java.awt.*;
public class DrawingOval extends Frame
  public DrawingOval()
    CanvasEx cx = new CanvasEx();
    cx.setSize(125, 100);
    add(cx, "North");
    setSize(300, 200); 
  public static void main(String args[])
    new DrawingOval();
class CanvasEx extends Canvas
  public void paint(Graphics g)
    g.fillOval(75, 10, 150, 75);

To write on canvas, our class should extend the java.awt.Canvas class. Here, CanvasEx extends Canvas. The main class is DrawingOval extending Frame. CanvasEx object is created and added to the frame on North side. Canvas is colored pink just for identification. The object of Canvas is tied to a frame to draw painting. On the canvas, oval filled with blue color is drawn.

Leave a Comment

Your email address will not be published.