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