22

I need to set the caret position manually in my code. There is a getCaretPosition() under javafx.scene.control.TextInputControl but there is no setter method.

How can I set the caret position?

Aubin
  • 14,617
  • 9
  • 61
  • 84
Anuruddha
  • 1,367
  • 6
  • 19
  • 38

4 Answers4

39
TextArea ta = new TextArea();
ta.setText("1234567890");
ta.positionCaret(4);
Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
8

You can use the positionCaret function as mentioned before. But make sure to wrap it in Platform.runLater. Otherwise it might not work at all.

Platform.runLater( new Runnable() {
    @Override
    public void run() {
        textArea.positionCaret( 0 );
    }
});
Jewe
  • 91
  • 1
  • 4
2

There are two method in TextInputControl that allow manipulation of caret position. These are :-

  1. selectPositionCaret(int pos) - Selects the text between the last caret position up to the current caret position that you entered.

  2. positionCaret(int pos) - Sets the current caret position clearing the previous selection as well.

So i think in your case you want to use the positionCaret method to set the position without any selections.

0

if you want to add it at the end of your TextField you can do the next

TextFieldName.positionCaret(TextFieldName.getText().length());

this will add the Curser at The end .

Ahmad Ellamey
  • 331
  • 2
  • 7