Introduction to AWT and Applets · Introduction to Java Programming

Drawing in a Frame

Watch lectures

Drawing in a Frame

1. How Drawing Works (beginner)

AWT draws via paint(Graphics g) (called on show/resize!). Graphics g = pen (color, font, shapes!). Override paint, NEVER call directly (use repaint() to request!).

2. Code — Shapes Sampler (exam sketch!)

import java.awt.*;
class Draw extends Frame {
    Draw() { setSize(300, 200); setVisible(true); }
    public void paint(Graphics g) { // called by JVM!
        g.setColor(Color.RED);
        g.drawLine(10, 50, 100, 50);   // line!
        g.drawRect(10, 70, 60, 40);    // outline box!
        g.fillOval(100, 70, 60, 60);   // filled circle!
        g.drawString("hi!", 10, 150);  // text!
    }
}
new Draw();

3. Key Methods (exam table!)

Method Draws
drawLine(x1,y1,x2,y2) line
drawRect/fillRect outline/filled box
drawOval/fillOval circle/ellipse
drawString(s,x,y) text
setColor(c) pen color!

Coords: (0,0) top-left! y grows DOWN (unlike maths!).

4. Traps

  • Call repaint(), not paint() (JVM passes correct g!).
  • draw = outline, fill = solid (exam mixes!).
  • Title bar eats top (~30px) — start y ≥ 50!

5. Exam Points

  • Shapes program + table — 5-7 marks, very frequent.
  • paint vs repaint, coords — 3 marks, frequent.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules