Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The Canvas class in AWT inherits the Component class. Canvas class is a part of Java AWT. A canvas is a blank rectangular area where the user can draw or trap input from the user. We will learn more about AWT Canvas in upcoming sections.
In the following example, we are creating a Canvas in the Frame and painting a red-colored oval inside it.
import java.awt.*;
public class CanvasExample1
{
// class constructor
public CanvasExample1()
{
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
// setting layout, size and visibility of frame
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CanvasExample1();
}
}
// class which inherits the Canvas class
// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
// paint() method to draw inside the canvas
public void paint(Graphics g)
{
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
You can also try this code with Online Java Compiler
In this example, we are creating an empty canvas and writing some text, and setting some color to the text. We have also set the size and color of the canvas.
import java.awt.*;
import javax.swing.*;
class canvas extends JFrame {
canvas()
{
super("canvas");
//creating an empty canvas
Canvas canvasobj = new Canvas() {
// paint the canvas
public void paint(Graphics g)
{
// set color to red
g.setColor(Color.red);
// set Font
g.setFont(new Font("Bold", 1, 20));
// draw a string
g.drawString("This is a canvas", 150, 150);
}
};
canvasobj.setBackground(Color.black);
add(canvasobj);
setSize(400, 300);
show();
}
// Main Method
public static void main(String args[])
{
canvas canvasobj = new canvas();
}
}
You can also try this code with Online Java Compiler
It stands for Abstract Window Toolkit. It is an API that Java programmers use to create GUI(Graphical User Interface) objects such as scroll bars, windows, and buttons.
Which library package needs to be imported to use awt canvas?
We need to import class java.awt.Canvas
If we want to display ellipses and rectangles on a screen, should we use a canvas or a JPanel?
It depends on whether we are using Swing or AWT. If we are using swing, then it is recommended to use only swing components, so we should use Jpanel, but if we are using awt then canvas should be used. Mixing swing and AWT components in the same GUI lead to unexpected results.
Conclusion
In this article, we have discussed the AWT Canvas through different examples. We also discussed the constructors and methods of the AWT Canvas.