How do I draw a string in Java 2D?

The code snippet below show you how to draw a string using Graphics2D. The drawString() method accept the string to be drawn and their x and y coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint() method.

package org.kodejava.example.awt.geom;

import javax.swing.*;
import java.awt.*;

public class DrawString extends JPanel {
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        // Define rendering hint, font name, font style and font size
        g2.setFont(new Font(Font.SERIF, Font.ITALIC, 40));
        // Draw Hello World String
        g2.drawString("Hello World!", 100, 100);

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Draw String Demo");
        frame.add(new DrawString());
        frame.setSize(400, 300);

Run the snippet and you’ll see the following screen:

Draw String Demo

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply