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:

Latest posts by Wayan (see all)
- How do I scale and paint an image in Swing? - December 1, 2026
- How do I arrange components using BorderLayout in Java Swing? - December 1, 2026
- How do I map a Java class to a database table? - November 30, 2026