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!).
setFontaffects LATER draws only (order matters!).drawStringwithnull→ NPE!
5. Exam Points
- Font + color + drawString program — 5 marks, frequent.
- Baseline + centering — 3 marks, frequent.