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 {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
       
        //
        // Define rendering hint, font name, font style and font size
        //
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font(Font.SERIF, Font.ITALIC, 40));
        g2.setPaint(Color.BLUE);
       
        //
        // 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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new DrawString());
        frame.pack();
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

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

Draw String Demo

How do I draw a vertical text in Java 2D?

To draw a text / string vertically we need to do a transform on the Graphics2D object. First, create an instance of AffineTransform and set the rotation using the setToRotation() method. And then pass this transform object into g2.setTransform() method.

package org.kodejava.example.awt.geom;

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

public class DrawVerticalText extends JPanel {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        //
        // Define rendering hint, font name, font style and font size
        //
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font(Font.SERIF, Font.BOLD, 20));

        //
        // Rotate 90 degree to make a vertical text
        //
        AffineTransform at = new AffineTransform();
        at.setToRotation(Math.toRadians(90), 10, 10);
        g2.setTransform(at);
        g2.drawString("This is a vertical text", 10, 10);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Draw Vertical Text Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new DrawVerticalText());
        frame.pack();
        frame.setSize(200, 300);
        frame.setVisible(true);
    }
}

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

Draw Vertical Text Demo