以下示例演示了如何禁用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); } }); } }
上面的代码片段的输出是: