如果Java Swing JTextField获得焦点,则会标记其所有文本。

现在,我想修改行为,以便如果用户现在按向右箭头,则光标应设置为开头的文本(位置0)。

我能够获得RIGHT Key事件并将光标设置到位置0,
但是我不知道如何将RIGHT Key事件传递给原始代码,以便它可以处理正常的行为。

JTextField preisFieldEUR = new JTextField(…);

AbstractAction right = new AbstractAction() {
  @Override
  public void actionPerformed(ActionEvent e) {
    if (preisFieldEUR.getSelectionEnd() - preisFieldEUR.getSelectionStart() == preisFieldEUR.getText().length()) {
      preisFieldEUR.setSelectionStart(0);
      preisFieldEUR.setSelectionEnd(0);
    } else {
      // Todo: How to pass this event to the original keyboard handler to
      // keep the normal behaviour?
    }
  }
};

preisFieldEUR.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), right);


非常感谢您的帮助!

最佳答案

您需要这样的东西:

Action oldAction = preisFieldEUR.getActionMap().get("caret-forward"); // probably another parameter?
AbstractAction right = new AbstractAction() {
  @Override
  public void actionPerformed(ActionEvent e) {
    if (preisFieldEUR.getSelectionEnd() - preisFieldEUR.getSelectionStart() == preisFieldEUR.getText().length()) {
      preisFieldEUR.setSelectionStart(0);
      preisFieldEUR.setSelectionEnd(0);
    } else {
        oldAction.actionPeformed(e)
    }
  }
};

10-08 18:10