Drawing with the Graphics Class
Site Admin
· 11 Sep 2026
· 1 views
The Graphics Context
Every paint operation goes through the abstract Graphics class. Override paint(Graphics g) and use its drawing methods to draw on a component such as a Canvas.
Drawing Shapes
import java.awt.*;
class ShapeCanvas extends Canvas {
public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawLine(20, 20, 200, 20);
g.drawRect(20, 50, 120, 80);
g.fillOval(170, 50, 100, 80);
g.drawString("Hello Graphics", 30, 180);
}
}Add the canvas to a Frame, and every window redraw calls paint() again.


Key Points
- paint(Graphics) is called automatically when the component needs drawing.
- graphics are non-persistent: requests
repaint()to redraw after changes. - All colors, fonts and text also go through the Graphics object.