Java如何在JTextArea中禁用键盘事件?
以下示例演示了如何禁用JTextArea和JScrollPane使用中的某些键InputMap。在disableKeys()方法下面我们禁用方向键,包括UP,DOWN,LEFT和RIGHT。
让我们看看下面的代码片段:
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaDisableKeyDemo extends JFrame {
public TextAreaDisableKeyDemo() {
initialize();
}
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");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextAreaDisableKeyDemo().setVisible(true);
}
});
}
}上面的代码片段的输出是:
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短