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.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.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC, 40));

        // Draw Hello World String
        g2.drawString("Hello World!", 50, 100);

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

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

Draw String Demo

How do I define a font for text object in iText?

We can set font style for text object such as Chunk, Phrase, Paragraph, etc using the com.itextpdf.text.Font class. We can define the font face, size, style and its color using this class.

package org.kodejava.example.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;


public class FontDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("FontDemo.pdf"));

            // Creates some fonts
            Font largeBold = new Font(Font.FontFamily.COURIER, 32,
            Font smallItalic = new Font(Font.FontFamily.HELVETICA, 10,
            Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
                    Font.ITALIC | Font.UNDERLINE, BaseColor.RED);

            // Creates chunk, phrase and paragraph with font
            // information.
            Chunk chunk = new Chunk("Hello World", largeBold);
            Phrase phrase =
                    new Phrase("The quick brown fox ", smallItalic);
            Paragraph paragraph =
                    new Paragraph("jumps over the lazy dog", redFont);

        } catch (DocumentException | FileNotFoundException e) {
        } finally {

Maven Dependencies

<!-- -->