1

I'm really struggling to find the functionality (if it even exists), to move a JTextFields cursor by clicking a Button, instead of using the mouse.

For instance, I have my text field with a string added. By clicking a back button, the cursor will move back through the string, 1 position at a time or forward depending on which button is pressed.

I can do it with the mouse, just click and type, but I actually need to have it button based so that the user can choose to use the keypad to enter a name or just click into the JTextArea and type away.

Is it possible? What methods should I look for if so.

Thank you.

Patrick
  • 4,532
  • 2
  • 26
  • 32
JoshuaTree
  • 1,211
  • 14
  • 19

1 Answers1

3

These are sample buttons that are doing what you're asking for:

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

They are moving the carot in the textfield txtAbc with 1 position per click. Notice, that you need to disable the focusable flag for both buttons, or the focus of your textfield will be gone if you click one of these buttons and you can't see the carot anymore.

To avoid exceptions if you're trying to move the carot out of the textfield boundaries (-1 or larger than the text length), you should check the new values (for example in dedicated methods):

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);
}
Tom
  • 16,842
  • 17
  • 45
  • 54
  • This is exactly what I was looking for. Now I can browse through the texfield using the buttons. MANY THANKS! Building a calculator and need to edit the field with keyboard and buttons. THANK YOU – JoshuaTree Oct 18 '14 at 14:09