by Dinesh Thakur

The java.awt.Canvas component is a "web" rectangular area for supporting drawing operations defined by the application as well as monitor input events performed by the user. This component does not encapsulate another feature except the support for rendering, providing a base class for creating new components.

This object can be used for double buffering techniques to avoid the effects of blinking, first painting on canvas and then adding to the canvas once already built screen.

Once we have drawn only the Canvas add any other ingredient. It is quite usual to derive a class of Canvas to redefine the functions we want to draw shapes and then add this new component to the relevant panel or window. The method that will schedule what we always draw.
public void paint(Graphics g)
This class provides a constructor and two methods of which we selected:

Method

Description

Canvas ()

Constructs a new Canvas object.

paint (Graphics)

Renders the Canvas object through its graphics context.

 

import java.applet.Applet;

import java.awt.*;
import java.awt.event.*;
/*<APPLET CODE=CanvasJavaExampleAppletSwing.class WIDTH=400 HEIGHT=200></APPLET>*/
public class CanvasJavaExampleAppletSwing extends java.applet.Applet implements MouseListener
  {
     graphicsCanvas GC;
     Button BtnOne;
     public void init()
       {
         GC= new graphicsCanvas();
         GC.setSize(120,120);
         add(GC);
         addMouseListener(this);
       }
            public void mousePressed(MouseEvent e1){}
            public void mouseClicked(MouseEvent e1)
           {
              for(int loop_index = 0; loop_index < 150; loop_index++)
                {      
                   GC.setLocation(loop_index, 0);
                }
           }
              public void mouseReleased(MouseEvent e1){}
              public void mouseEntered(MouseEvent e1){}
              public void mouseExited(MouseEvent e1){}
  }
              class graphicsCanvas extends java.awt.Canvas 
              {
                  public void paint (Graphics gr)
                 {
                    gr.drawOval(10, 50, 40, 40);
                    gr.drawLine(10, 50, 50, 90);
                    gr.drawLine(50, 50, 10, 90);
                 }
              }

Java AWT Canvas Example