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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024