O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); 
    } 
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required