Home »
Java programming language
Java AWT Canvas
Java | AWT Canvas: In this tutorial, we will look at one of the Java AWT components, the AWT Canvas with example.
Submitted by Saranjay Kumar, on April 29, 2020
Canvas is a GUI component that creates a rectangular box on the screen. It can be used to draw shapes or print text, it acts as a canvas. It can also be used to take user inputs. It is called so because it is like a canvas on which artists draw. With the correct programming, we can use the Canvas class to design a paint-like application, where the user can freely draw any shape or object he chooses.
We can use MouseListeners to trap user input when they interact with the Canvas object. The object generates MouseEvents whenever there is a mouse click, move, drag, etc. We can use these events and implement the MouseListener interface to utilize the full power of the Canvas object. We shall learn more about event handling in later sections.
Consider the following code -
import java.awt.*;
import javax.swing.*;
public class CreateCanvas extends Canvas {
CreateCanvas() {
Frame f = new Frame();
setBackground(Color.BLUE);
setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
f.setSize(500, 500);
f.add(this);
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.drawOval(150, 100, 70, 50);
g.setColor(Color.RED);
g.drawString("Java is the best", 100, 180);
}
public static void main(String[] args) {
CreateCanvas ob = new CreateCanvas();
}
}
Output
As can be seen, we have created a canvas object of size 300 pixels by 200 pixels. Our class extends the Canvas class and overwrites its paint method. Initially, we created a blank canvas. The paint method of the canvas class gets automatically called and need not be specially called by the programmer. The default paint method just clears the canvas and it is not necessary to overwrite this, but this method should be overwritten for any fruitful application of the canvas class.
We set the background color of the canvas by calling the setBackground() method. Since our class extends the Canvas class, we need not specially create an object of Canvas class to call a method. We can set the size of the Canvas using the setSize() method, where we pass two integers – the width and height of the Canvas object.
All the drawings and texts that are displayed on the canvas have to be written inside the paint method. We utilize the Graphics class here, which is created by default by the Canvas object itself and can be used to draw on the Canvas.
The setColor() method of the Graphics object changes the color which is used to draw. The drawOval() method draws the outline of an oval on the screen and requires 4 parameters – The x coordinate, y coordinate, width, and height.