Home ยป Working with JTextArea in Java Swing tutorial with code examples

Working with JTextArea in Java Swing tutorial with code examples

JTextArea is a multi-line text component in Java Swing that allows users to input and display multiple lines of text.

It is a versatile component used for creating text editors, chat applications, and other applications that require text input or output in a multi-line format.

In this tutorial, we'll cover the basics of creating and using JTextArea, customizing it, adding scrollbars, and interacting with it programmatically.

Basic Structure of JTextArea

To create a JTextArea, you use its constructor and specify parameters such as the number of rows and columns. You can also set its initial text.

Basic JTextArea Constructor:

JTextArea textArea = new JTextArea(10, 30); // 10 rows and 30 columns

The JTextArea class is part of the javax.swing package, so you need to import it before use.

1. Creating a Simple JTextArea

Letโ€™s start with a basic example of creating a JTextArea and adding it to a JFrame.

Example 1: Basic JTextArea

import javax.swing.*;

public class JTextAreaExample1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextArea Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            // Create a JTextArea with 10 rows and 30 columns
            JTextArea textArea = new JTextArea(10, 30);
            
            frame.add(textArea); // Add JTextArea to the frame
            frame.setVisible(true);
        });
    }
}

Explanation:

We create a JTextArea with 10 rows and 30 columns, meaning the text area can display 10 lines of text and about 30 characters per line.
The text area is added to the frame directly, and the frame is made visible.

2. Setting Initial Text in JTextArea

You can initialize the JTextArea with some text using its constructor or the setText() method.

Example 2: Setting Initial Text

import javax.swing.*;

public class JTextAreaExample2 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextArea with Initial Text");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            // Create a JTextArea with initial text
            JTextArea textArea = new JTextArea("This is the initial text in the JTextArea.", 10, 30);

            frame.add(textArea);
            frame.setVisible(true);
        });
    }
}

Explanation:

The JTextArea is initialized with some text (“This is the initial text in the JTextArea”).
The text area will display this initial content when the frame is opened.

3. Adding Scrollbars to JTextArea

By default, a JTextArea doesnโ€™t have scrollbars, but you can add them using a JScrollPane. This allows the text area to handle long text that exceeds its visible area.

Example 3: Adding Scrollbars to JTextArea

import javax.swing.*;

public class JTextAreaExample3 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextArea with Scrollbars");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);

            // Wrap the JTextArea in a JScrollPane to add scrollbars
            JScrollPane scrollPane = new JScrollPane(textArea);

            frame.add(scrollPane); // Add the JScrollPane (with JTextArea inside) to the frame
            frame.setVisible(true);
        });
    }
}

Explanation:

A JScrollPane is used to wrap the JTextArea, automatically adding scrollbars when needed.
Now, when the content exceeds the visible area, scrollbars will appear, allowing the user to scroll through the text.

4. Line Wrapping in JTextArea

By default, JTextArea does not wrap text lines. You can enable line wrapping using the setLineWrap() and setWrapStyleWord() methods.

setLineWrap(true) enables line wrapping.
setWrapStyleWord(true) ensures that lines are wrapped at word boundaries rather than splitting words in the middle.

Example 4: Enabling Line Wrapping

import javax.swing.*;

public class JTextAreaExample4 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextArea with Line Wrapping");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);

            // Enable line wrapping and wrap at word boundaries
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);

            JScrollPane scrollPane = new JScrollPane(textArea);
            frame.add(scrollPane);

            frame.setVisible(true);
        });
    }
}

Explanation:

The setLineWrap(true) method enables line wrapping.
The setWrapStyleWord(true) method ensures that words are not split in the middle when wrapping.

5. Customizing JTextArea Font and Colors

You can customize the appearance of the JTextArea by setting the font, background color, and text color.

Example 5: Customizing Font and Colors

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

public class JTextAreaExample5 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Customized JTextArea");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);
            
            // Set a custom font: Font(name, style, size)
            textArea.setFont(new Font("Serif", Font.BOLD, 16));
            
            // Set background and foreground (text) colors
            textArea.setBackground(Color.LIGHT_GRAY);
            textArea.setForeground(Color.BLUE);

            JScrollPane scrollPane = new JScrollPane(textArea);
            frame.add(scrollPane);

            frame.setVisible(true);
        });
    }
}

Explanation:

The setFont() method is used to change the font to a bold, 16-point serif font.
The background color is set to light gray, and the text color is set to blue using setBackground() and setForeground().

6. Reading and Writing Text from JTextArea

You can retrieve the text from a JTextArea using getText() and set the text using setText(). This allows you to dynamically update the text content or read what the user has entered.

Example 6: Reading and Setting Text Dynamically

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTextAreaExample6 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextArea Reading and Writing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);
            JButton button = new JButton("Update Text");

            // Set initial text in the JTextArea
            textArea.setText("This is the initial text.");

            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Read text from JTextArea
                    String currentText = textArea.getText();

                    // Append some new text
                    textArea.setText(currentText + "\nNew text added.");
                }
            });

            JPanel panel = new JPanel();
            panel.add(new JScrollPane(textArea));
            panel.add(button);

            frame.add(panel);
            frame.setVisible(true);
        });
    }
}

Explanation:

The getText() method retrieves the current text from the JTextArea.
The setText() method updates the text displayed in the text area. In this example, we append new text to the existing content.

7. Disabling and Enabling JTextArea

You can control whether the JTextArea is editable by using the setEditable() method. This is useful when you want to display text but prevent the user from modifying it.

Example 7: Disabling Editing in JTextArea

import javax.swing.*;

public class JTextAreaExample7 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Non-editable JTextArea");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);
            textArea.setText("This text cannot be edited.");

            // Disable editing
            textArea.setEditable(false);

            frame.add(new JScrollPane(textArea));
            frame.setVisible(true);
        });
    }
}

Explanation:

The setEditable(false) method prevents the user from editing the content of the JTextArea.
The text area is still scrollable and can display text, but the user cannot modify it.

8. Listening to Text Changes in JTextArea

You can attach a DocumentListener to the JTextArea to listen for changes in the text. This is useful when you need to take action based on the user's input.

Example 8: Listening for Text Changes

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class JTextAreaExample8 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Listening for Text Changes");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            JTextArea textArea = new JTextArea(10, 30);
            JLabel statusLabel = new JLabel("Text length: 0");

            // Add a DocumentListener to listen for changes in the JTextArea
            textArea.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateTextLength();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateTextLength();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateTextLength();
                }

                // Update the label to show the current length of the text
                private void updateTextLength() {
                    statusLabel.setText("Text length: " + textArea.getText().length());
                }
            });

            JPanel panel = new JPanel();
            panel.add(new JScrollPane(textArea));
            panel.add(statusLabel);

            frame.add(panel);
            frame.setVisible(true);
        });
    }
}

Explanation:

We attach a DocumentListener to the JTextArea to listen for changes in the document (insertion, removal, etc.).
Whenever the text is updated, the label displays the current length of the text.

Conclusion

JTextArea is a powerful and flexible text component in Java Swing that allows users to input or display multi-line text.

It supports features like scrolling, line wrapping, font customization, and event handling. You can read and modify its content programmatically, making it ideal for use in text editors, chat applications, and more.

Summary of Key Points:

Basic JTextArea: Create a JTextArea with a specified number of rows and columns.
Initial Text: Set initial text using the constructor or setText().
Scrollbars: Add scrollbars using JScrollPane.
Line Wrapping: Enable line wrapping with setLineWrap(true) and setWrapStyleWord(true).
Customization: Change the font, background, and text colors using setFont(), setBackground(), and setForeground().
Reading and Writing: Retrieve and update text with getText() and setText().
Disabling Editing: Use setEditable(false) to make the text area read-only.
Text Change Listener: Attach a DocumentListener to monitor changes to the text in the text area.

You may also like