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.swing;

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

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

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

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaFontDemo::showFrame);
    }

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

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

        // Sets JTextArea font and color.
        Font font = new Font("Segoe Script", Font.BOLD, 20);
        textArea.setFont(font);
        textArea.setForeground(Color.BLUE);
        JScrollPane scrollPane = new JScrollPane(textArea);

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

Here is the program screenshot of the code snippet above:

JTextArea Font and Color Demo

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.