Introduction to AWT and Applets · Introduction to Java Programming

Displaying Text in a Frame

Watch lectures

Displaying Text in a Frame

1. How Text Draws (beginner)

g.drawString("text", x, y) paints text at baseline (x,y = LEFT-BOTTOM of text!). Control look with Font + Color first!

2. Code — Styled Text (exam program!)

import java.awt.*;
class Text extends Frame {
    Text() { setSize(300, 200); setVisible(true); }
    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.setFont(new Font("Arial", Font.BOLD, 20)); // name, style, size!
        g.drawString("Hello Java!", 50, 100); // baseline at y=100!
        g.setColor(Color.RED);
        g.setFont(new Font("Serif", Font.ITALIC, 14));
        g.drawString("marks: 87", 50, 130);
    }
}
new Text();

Font styles: Font.PLAIN, BOLD, ITALIC, BOLD+ITALIC (Font.BOLD | Font.ITALIC!).

3. Center Text (viva trick!)

FontMetrics fm = g.getFontMetrics(); // measurer!
int w = fm.stringWidth("Hello");     // pixels wide!
g.drawString("Hello", (300 - w) / 2, 100); // centered!

4. Traps

  • y = BASELINE (letters like 'g' dip below!). y=20 may clip top (start ≥ 50!).
  • setFont affects LATER draws only (order matters!).
  • drawString with null → NPE!

5. Exam Points

  • Font + color + drawString program — 5 marks, frequent.
  • Baseline + centering — 3 marks, frequent.
Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.

← All Introduction to Java Programming modules