使用低級別的聽衆像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綁定。 –