How do I disable keyboard events in JTextArea?

The following example demonstrate how to disable some keys in JTextArea and JScrollPane using the InputMap. In the disableKeys() method below we disable the arrow keys including the UP, DOWN, LEFT and RIGHT.

Let’s see the code snippet below:

package org.kodejava.swing;

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

public class TextAreaDisableKeyDemo extends JFrame {
    public TextAreaDisableKeyDemo() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new TextAreaDisableKeyDemo().setVisible(true));
    }

    private void initialize() {
        setSize(500, 200);
        setTitle("Disable Keys Demo");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JTextArea textArea = new JTextArea("Hello World!");
        JScrollPane scrollPane = new JScrollPane(textArea);
        disableKeys(textArea.getInputMap());
        disableKeys(scrollPane.getInputMap(
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));

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

    private void disableKeys(InputMap inputMap) {
        String[] keys = {"UP", "DOWN", "LEFT", "RIGHT"};
        for (String key : keys) {
            inputMap.put(KeyStroke.getKeyStroke(key), "none");
        }
    }
}

The output of the code snippet above is:

Disable Keyboard Events in JTextArea

How do I create a single line JTextArea?

The following example will show you how to create a single line JTextArea. A single line means that you cannot insert a new line in the text area. When pressing the enter key it will be replaced by a space.

This can be done by putting a property called filterNewlines and set its value to Boolean.TRUE into the document model of the JTextArea.

package org.kodejava.swing;

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

public class SingleLineTextArea extends JFrame {
    private SingleLineTextArea() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new SingleLineTextArea().setVisible(true));
    }

    private void initialize() {
        setSize(500, 200);
        setTitle("Single Line Text Area");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);

        // Filter a new line, pressing enter key will be replaced
        // with a space instead.
        textArea.getDocument().putProperty("filterNewlines",
                Boolean.TRUE);

        JScrollPane scrollPane = new JScrollPane(textArea);

        // Pressing the Save button print out the text area text
        // into the console.
        JButton button = new JButton("Save");
        button.addActionListener(e -> System.out.println(textArea.getText()));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}

The screenshot of the result of the code snippet above is:

Single Line JTextArea Demo

How do I move focus from JTextArea using TAB key?

The default behavior when pressing the tabular key in a JTextArea is to insert a tab spaces in the text area. In this example you’ll see how to change this to make the tab key to transfer focus to other component forward or backward.

The main routine can be found in the key listener section. When the tab key is pressed we will tell the text area to transfer to focus into other component. Let’s see the code snippet below.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TextAreaTabMoveFocus extends JFrame {
    public TextAreaTabMoveFocus() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new TextAreaTabMoveFocus().setVisible(true));
    }

    private void initialize() {
        setSize(500, 200);
        setTitle("JTextArea TAB DEMO");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JTextField textField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        final JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);

        // Add key listener to change the TAB behavior in
        // JTextArea to transfer focus to other component forward
        // or backward.
        textArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_TAB) {
                    if (e.getModifiersEx() > 0) {
                        textArea.transferFocusBackward();
                    } else {
                        textArea.transferFocus();
                    }
                    e.consume();
                }
            }
        });

        getContentPane().add(textField, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(passwordField, BorderLayout.SOUTH);
    }
}

The output of the code snippet above is:

JTextArea Move Focus Using Tab

How do I read text file into JTextArea?

Using the read(Reader in, Object desc) method inherited from the JTextComponent allow us to populate a JTextArea with text content from a file. This example will show you how to do it.

In this example we use an InputStreamReader to read a file from our application resource. You could use other Reader implementation such as the FileReader to read the content of a file. Let’s see the code below.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;

public class PopulateTextAreaFromFile extends JPanel {
    public PopulateTextAreaFromFile() {
        initialize();
    }

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

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

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

    private void initialize() {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        try {
            // Read some text from the resource file to display in
            // the JTextArea.
            textArea.read(new InputStreamReader(Objects.requireNonNull(
                    getClass().getResourceAsStream("/data.txt"))), null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

Read Text File into JTextArea

How do I select all text in JTextArea?

Selecting all text in the JTextArea component can be done by using the selectAll() method. In the example below we use a button action to do the selection. After select the text we transfer focus back to the JTextArea so that the highlighted text is shown.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaSelectAll();
        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(TextAreaSelectAll::showFrame);
    }

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

        final JTextArea textArea = new JTextArea(
                "The quick brown fox jumps over the lazy dog.");
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        final JButton button1 = new JButton("Select All");
        button1.addActionListener(e -> {
            textArea.selectAll();

            // Transfer focus to JTextArea to show the selected
            // text.
            button1.transferFocusBackward();
        });
        final JButton button2 = new JButton("Get Selected Text");
        button2.addActionListener(e -> {
            String text = textArea.getSelectedText();
            System.out.println("Text = " + text);
        });

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(button1);
        buttonPanel.add(button2);

        this.add(pane, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }
}

And here the screenshot of the code snippet above:

JTextArea Select All Text

How do I append text to JTextArea?

To append text to the end of the JTextArea document we can use the append(String str) method. This method does nothing if the document is null or the string is null or empty.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaAppendText();
        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(TextAreaAppendText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick brown fox ";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        String appendText = "jumps over the lazy dog.";
        textArea.append(appendText);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

JTextArea Append Text Demo

How do I insert a text in a specified position in JTextArea?

The insert(String str, int pos) of the JTextArea allows us to insert a text at the specified position. In the example below we insert brown and over words into the current JTextArea text.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaInsertText();
        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(TextAreaInsertText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick fox jumps the lazy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.insert("brown ", 10);
        textArea.insert("over ", 26);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The screenshot of the result from the code snippet above is:

JTextArea Insert Text Demo

How do I replace text in the JTextArea?

In this example you’ll see how to use the replaceRange(String str, int start, int end) method to replace a string in the JTextArea from the start position to the end position with the specified string.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaReplaceText();
        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(TextAreaReplaceText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick white fox jumps over the sleepy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.replaceRange("brown", 10, 15);
        textArea.replaceRange("lazy", 35, 41);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The screenshot of the code snippet above is:

JTextArea Replace Text Demo

How do I set and get the contents of JTextArea?

To set and get the contents of a JTextArea you can use the setText(String text) and getText() methods. In the code below we create a JTextArea and sets its contents after we create a new instance of JTextArea. To get the contents we use the action on a button. When the button is pressed the contents of the JTextArea is read using the getText() method. This method return a String object.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaGetContent();
        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(TextAreaGetContent::showFrame);
    }

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

        final JTextArea textArea = new JTextArea();

        // Set the contents of the JTextArea.
        String text = "The quick brown fox jumps over the lazy dog.";
        textArea.setText(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JButton button = new JButton("Get Contents");
        button.addActionListener(e -> {
            // Get the contents of the JTextArea component.
            String contents = textArea.getText();
            System.out.println("contents = " + contents);
        });

        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
    }
}

The output of the code snippet above is:

Set and Get the Content of JTextArea

How do I set the tab size in JTextArea?

In this example you will be shown how to set or change the tab size for the JTextArea component. You can use the setTabSize(int size) to define the tab size. For this demo we create a combo box that have some integer values which will be used to define the tab size. When you change the selected item in the combo box the JTextArea tab size will be change immediately.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaSetTabSize();
        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(TextAreaSetTabSize::showFrame);
    }

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

        JLabel label = new JLabel("Tab size: ");
        Object[] items = {2, 4, 8, 10, 20};
        final JComboBox<Object> comboBox = new JComboBox<>(items);

        JPanel tabPanel = new JPanel(new FlowLayout());
        tabPanel.add(label);
        tabPanel.add(comboBox);

        this.add(tabPanel, BorderLayout.NORTH);

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        // Sets the number of characters to expand tabs to.
        textArea.setTabSize((Integer) comboBox.getSelectedItem());
        comboBox.addItemListener(e -> textArea.setTabSize(
                (Integer) comboBox.getSelectedItem()));

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

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

The output of the code snippet above is:

JTextArea Tab Size Demo