Way2Java

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);
    cx.setBackground(Color.pink);
    add(cx, "North");
    
    setSize(300, 200); 
    setVisible(true);
  }
  public static void main(String args[])
  {
    new DrawingOval();
  }
}
class CanvasEx extends Canvas
{
  public void paint(Graphics g)
  {
    g.setColor(Color.blue);
    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.

Java AWT Canvas Freelance Drawing

It is another program on canvas to draw freely with the mouse on the frame. By pressing and dragging the left mouse button on the canvas, any figure can be drawn. When right button is clicked, every earlier drawing is erased.

import java.awt.*;
import java.awt.event.*;
public class FreeLanceDrawing extends Frame
{ 	
  public FreeLanceDrawing()
  { 
    Canvas cvas = new DrawCanvas();
    cvas.setBackground(Color.cyan);
    add("Center", cvas); 
    
    setTitle("Draw As You Like Please");
    setSize(400, 450);
    setVisible(true);
  }
  public static void main(String args[])
  {
     new  FreeLanceDrawing();
  }
}
class DrawCanvas extends Canvas implements MouseListener, MouseMotionListener
{ 
  final int CIRCLESIZE = 20; 		     // becomes circle radius
  private Point lineBegin = new Point(0, 0); // point where line starts
  public DrawCanvas()
  { 
    addMouseListener(this);
    addMouseMotionListener(this);
  }  
                                             // override all the five abstract methods of ML
   public void mouseClicked(MouseEvent e)  {  }
   public void mouseEntered(MouseEvent e)  {  }
   public void mouseExited(MouseEvent e)   {  }
   public void mouseReleased(MouseEvent e) {  }

   public void mousePressed(MouseEvent e)
   {   
     if (e.isMetaDown())		     // for right mouse button
         setForeground(getBackground());     // match foreground to 
     else 			             // background(for erasing affect)
	setForeground(Color.black);          //  set foreground for drawing
                                             //get the new start end of the line
        lineBegin.move(e.getX(), e.getY());  // place in comments for different affect
   }
                                             // override methods of MML
   public void mouseDragged(MouseEvent e)
   {  		
     Graphics g = getGraphics() ;   		
     if (e.isMetaDown())                     // erase existing graphics using an oval
          g.fillOval(e.getX() - (CIRCLESIZE/2), e.getY() - (CIRCLESIZE/2), CIRCLESIZE, CIRCLESIZE);
     else
	  g.drawLine(lineBegin.x, lineBegin.y, e.getX(), e.getY());

     lineBegin.move(e.getX(), e.getY()); 
   }                                         // place the above line in comments, you will see different output
   public void mouseMoved (MouseEvent e)   {  }
}


The program creates a DrawCanvas object to capture mouse movements on the canvas. It creates lines when left button is pressed and dragged. The click of a right button erases complete frame.

When a button is pressed, the mousePressed() handler is invoked. This handler sets the Point, lineBegin to the current mouse point.

isMetaDown() method of MouseEvent evaluates to true if the right button is pressed.

When the mouse is dragged holding left button pressed, the drawing starts. Now the mousePressed() method sets the foreground color to black and the mouseDragged() method draws a line all through the movement of the mouse.

How the earlier frame drawings are erased?

When the mouse is dragged holding the right button pressed, erasing happens. Now the mousePressed() method sets the foreground color to the background color; both colors matches and no drawing appears. The mouseDragged() method draws a fill oval with black color to erase all the area occupied by the oval.

The program does not make use of paint(Graphics g) method. This method cannot be used to draw in this case because the drawing action takes place in the mouseDragged() method. For this reason, the program uses getGraphics()method to obtain a Graphics instance and draws the whole drawing on Graphics instance. A graphics instance represents the drawing area of the container.

Following is the method signature

public java.awt.Graphics getGraphics();

getGraphics() method is defined in java.awt.Component class and inherited by Frame class.

The program implements both MouseListener (for mousePressed()) and MouseMotionListener (for mouseDragged()).

Because mousePressed() is defined in the MouseListener interface and mouseDragged() is defined in the MouseMotionListener interface, the program implements both interfaces.