How do I set the font and color of JTextArea?

To set the font and color of JTextArea we can use the setFont() and setForeground() methods of the JTextArea. To create a font we must define the font name, the font style and its size. For the colors we can uses the constant color values defined by the Color class.

package org.kodejava.example.swing;

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

public class TextAreaFontDemo extends JPanel {
    public TextAreaFontDemo() {
        initializeUI();
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));

        JTextArea textArea = new JTextArea(5, 40);
        textArea.setText("The quick brown fox jumps over the lazy dog.");

        //
        // Sets JTextArea font and color.
        //
        Font font = new Font("Arial", Font.ITALIC, 18);
        textArea.setFont(font);
        textArea.setForeground(Color.BLUE);
        JScrollPane scrollPane = new JScrollPane(textArea);

        this.add(scrollPane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new TextAreaFontDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TextAreaFontDemo.showFrame();
            }
        });
    }
}
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