Canvas.
In Core Java, the Component
subclass used for drawing and painting is java.awt.Canvas
. The Canvas
class provides an area in which you can draw graphics and perform custom painting. It allows you to override the paint
method to specify what should be drawn within the canvas.
Here’s a simple example:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyCanvas extends Canvas {
public void paint(Graphics g) {
// Your custom drawing code goes here
g.setColor(Color.red);
g.fillRect(50, 50, 100, 100);
}
public static void main(String[] args) {
Frame frame = new Frame(“Canvas Example”);
MyCanvas canvas = new MyCanvas();
frame.add(canvas);
frame.setSize(300, 300);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
In this example, MyCanvas
extends Canvas
and overrides the paint
method to draw a red rectangle. The Frame
is used to create a window that contains the canvas.