JTextField - 使用按钮移动光标

时间:2014-10-18 12:47:43

标签: java swing jbutton jtextfield

我真的很难找到功能(如果它存在的话), 通过单击JTextFields而不是使用鼠标来移动Button光标。

例如,我的文本字段添加了一个字符串。 通过单击后退按钮,光标将向后移动字符串,一次移动1个位置或向前移动,具体取决于按下哪个按钮。

我可以用鼠标做,只需点击并输入,但我实际上需要基于按钮,以便用户可以选择使用键盘输入名称或只需点击JTextArea和输入。

有可能吗?如果是这样,我应该寻找什么方法。

谢谢。

1 个答案:

答案 0 :(得分:3)

这些是正在执行您要求的示例按钮:

btnMoveLeft = new JButton("-");
btnMoveLeft.setFocusable(false);
btnMoveLeft.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent arg0) {
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left
  }
});
// omitted jpanel stuff

btnmoveRight = new JButton("+");
btnmoveRight.setFocusable(false);
btnmoveRight.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right
  }
});
// omitted jpanel stuff

他们正在文本字段txtAbc中移动carot,每次点击一个位置。请注意,您需要禁用两个按钮的focusable标记,否则如果单击其中一个按钮并且无法再看到carot,则文本字段的焦点将消失。

如果您试图将carot移出文本域边界(-1或大于文本长度),以避免异常,则应检查新值(例如,在专用方法中):

private void moveLeft(int amount) {
    int newPosition = txtAbc.getCaretPosition() - amount;
    txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition);
}

private void moveRight(int amount) {
    int newPosition = txtAbc.getCaretPosition() + amount;
    txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition);
}
相关问题