A Canvas object provides access to a Graphics object via its paint() method.
In Java, the Canvas
class and the Graphics
class are often used together for drawing graphics in a graphical user interface (GUI). Here’s the relationship between these two classes:
- Canvas Class:
- The
Canvas
class is part of the Abstract Window Toolkit (AWT) package (java.awt
). - It provides an area for drawing graphics on a component.
- The
- Graphics Class:
- The
Graphics
class is also part of the AWT package (java.awt
). - It is used for drawing on components, images, or other surfaces.
- The
Relationship:
- When you want to draw on a
Canvas
component, you typically override thepaint
method of theCanvas
class. - The
Graphics
object is passed to thepaint
method as a parameter. - You use methods of the
Graphics
class to perform drawing operations on theCanvas
.
Here’s a simple example:
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Frame;
class MyCanvas extends Canvas {public void paint(Graphics g) {
// Use the Graphics object (g) to draw on the Canvas
g.drawString(“Hello, Canvas!”, 20, 20);
}
}
public class CanvasExample {
public static void main(String[] args) {
Frame frame = new Frame(“Canvas Example”);
MyCanvas canvas = new MyCanvas();
frame.add(canvas);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
In this example, the paint
method of MyCanvas
is overridden to draw a string using the drawString
method of the Graphics
class. The Graphics
object (g
) is automatically passed to the paint
method by the system when it’s time to repaint the Canvas
.
In summary, the Canvas
class provides an area for drawing, and the Graphics
class provides the methods for performing drawing operations on that canvas.