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 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