Drawing Text

Problem

You need to draw text in a component.

Solution

Simply call the drawString ( ) method in the Graphics class:

// graphics/DrawStringDemo.java 
import java.awt.*; 
 
public class DrawStringDemo extends Component { 
    int textX = 10, textY = 20; 
    public void paint(Graphics g) { 
        g.drawString("Hello Java", textX, textY); 
    } 
    public Dimension getPreferredSize(  ) { 
        return new Dimension(100, 100); 
    } 
}

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.