Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component class.
Constructor of the Canvas class are :
- Canvas(): Creates a new blank canvas.
- Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration.
Commonly used Methods in Canvas Class
Method |
Explanation |
addNotify() |
Creates the peer of the canvas. |
createBufferStrategy(int n) |
Creates a new strategy for multi-buffering on this component. |
createBufferStrategy(int n, BufferCapabilities c) |
Creates a new strategy for multi-buffering on this component with the required buffer capabilities |
getBufferStrategy() |
Returns the BufferStrategy used by this component. |
paint(Graphics g) |
paints this component. |
update(Graphics g) |
updates this canvas. |
Below programs illustrate the use of Canvas Class :
- Program 1: To create a canvas and paint the canvas.
Java
import java.awt.*;
import javax.swing.*;
class canvas extends JFrame {
canvas()
{
super ( "canvas" );
Canvas c = new Canvas() {
public void paint(Graphics g)
{
g.setColor(Color.red);
g.setFont( new Font( "Bold" , 1 , 20 ));
g.drawString( "This is a canvas" , 100 , 100 );
}
};
c.setBackground(Color.black);
add(c);
setSize( 400 , 300 );
show();
}
public static void main(String args[])
{
canvas c = new canvas();
}
}
|
-
- Program 2: To create a canvas and add mouse listener to the canvas(a circle of radius 5 will appear at the points where mouse are clicked or dragged on the canvas).
Java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class canvas extends JFrame implements MouseListener, MouseMotionListener {
Canvas c;
canvas()
{
super ( "canvas" );
c = new Canvas() {
public void paint(Graphics g)
{
}
};
c.setBackground(Color.black);
c.addMouseListener( this );
c.addMouseMotionListener( this );
add(c);
setSize( 400 , 300 );
show();
}
public void mouseClicked(MouseEvent e)
{
Graphics g = c.getGraphics();
g.setColor(Color.red);
int x, y;
x = e.getX();
y = e.getY();
g.fillOval(x, y, 5 , 5 );
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
Graphics g = c.getGraphics();
g.setColor(Color.red);
int x, y;
x = e.getX();
y = e.getY();
g.fillOval(x, y, 5 , 5 );
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public static void main(String args[])
{
canvas c = new canvas();
}
}
|
Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/Canvas.html
Last Updated :
02 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...