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() {

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

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

        JTextArea textArea = new JTextArea("Hello World!");
        JScrollPane scrollPane = new JScrollPane(textArea);

        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

Leave a Reply

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