Java


Java Tutorial


Admission Enquiry Form

  

Java Swing Canvas Drawing

What is Canvas in Java?

Canvas is a rectangular blank area where the user can draw or from which the application can trap input from the user. Canvas class inherits the Component class.Canvas class is a part of Java AWT.




Example of Canvas in Java:

package com.compuhelp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

class Mycanvas extends Canvas implements MouseListener, MouseMotionListener {
JButton btn1;
int x1,y1,x2,y2;
Cursor cursor;

public Mycanvas()
{
x1=10;
y1=10;
y2=200;
x2=200;
btn1=new JButton("Brush Size ++");

cursor=new Cursor(Cursor.HAND_CURSOR);
addMouseMotionListener(this);
addMouseListener(this);
setCursor(cursor);
}   //end of cunstructor

@Override
public void paint(Graphics g) {
super.paint(g);
// g.drawString("compuhelp",x1,y1);
// g.drawOval(x1,y1,50,50);
//g.drawLine(x1,y1,x2,y2);
}//end of paint

/* @Override
public void update(Graphics g) {
super.update(g);
g.drawLine(x1,y1,x2,y2);
}*/

@Override
public void mouseClicked(MouseEvent e) {
// Graphics myg;
// myg=getGraphics();
//myg.drawString("Demo",x1,y1+20);
//myg.drawOval(x1,y1,50,50);
x1=e.getX();
y1=e.getY();
//update(myg);
//repaint();
}

@Override
public void mousePressed(MouseEvent e) {
x1=e.getX();
y1=e.getY();
//repaint();
}

@Override
public void mouseReleased(MouseEvent e) {
/*  Graphics g=getGraphics();
x2=e.getX();
y2=e.getY();
g.drawLine(x1,y1,x2,y2);*/
//repaint();
}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}
//adding mousemothion listener

@Override
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
setBackground(Color.white);
setForeground(Color.red);
x2=e.getX();
y2=e.getY();
//g.drawLine(x2,y2,x2,y2);
// g.drawOval(x2,y2,5,5);
g.fillOval(x2-2,y2-2,5,5);
//repaint();

//update(getGraphics());

}

@Override
public void mouseMoved(MouseEvent e) {

}
}//end of class
class MyFrame extends JFrame{
Mycanvas canvas;
public MyFrame(){
canvas=new Mycanvas();
add(canvas);
setTitle("use of canvas");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
}//end of constructor
}//end of class
public class Main {

public static void main(String[] args) {
new MyFrame();
}//end of main
}//end of class



Output

The code above will display :



The above code is written to use canvas for drawing using MouseListener and MouseMotionListener interface