使用低级别的听众像Swing文本组件,如JTextAreas KeyListeners时,你要小心,因为搞乱这些可能会导致文本组件行为不当。
更好的方法是使用DocumentListener,如果您正在寻找文档或DocumentFilter的更改,如果您想要侦听并阻止或更改之前的文本条目它发生。
如果你只是想要得到诸如向上箭头之类的关键字的通知,我会使用键绑定--JTextArea使用它自己来通知键响应并对其作出反应,并将键替换新的一个。如果您谨慎操作,您甚至可以在新操作中调用与按键相关的原始操作。例如:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class TextAreaTrapUp extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
public TextAreaTrapUp() {
// get JTextArea's InputMap and ActionMap
int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = textArea.getInputMap(condition);
ActionMap actionMap = textArea.getActionMap();
// get the up keystroke
KeyStroke upKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
String upKey = (String) inputMap.get(upKeyStroke); // get the input map's key for this keystorke
Action originalUpAction = actionMap.get(upKey); // and get the action map's original action for this key
Action newUpAction = new NewUpAction(originalUpAction); // create our new up action passing in the old one
actionMap.put(upKey, newUpAction); // and set this into our ActionMap
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
add(new JScrollPane(textArea));
}
// Action called when up-arrow pressed
private class NewUpAction extends AbstractAction {
private Action originalUpAction; // the original action
public NewUpAction(Action originalUpAction) {
this.originalUpAction = originalUpAction;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Up Arrow Pressed");
// if you want to move the caret up, then call the original action
// as well
if (originalUpAction != null) {
originalUpAction.actionPerformed(e);
}
}
}
private static void createAndShowGui() {
TextAreaTrapUp mainPanel = new TextAreaTrapUp();
JFrame frame = new JFrame("TextAreaTrapUp");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
请勿在Swing文本组件中使用KeyListener,因为它们会混淆组件的本机功能。有很多更好的方法来捕获这些组件中的按键,包括使用DocumentListener,DocumentFilters和Key绑定。 –