Set caret position in javafx.scene.control.TextArea and javafx.scene.control.TextField
Asked Answered
E

4

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?

Eonian answered 28/11, 2011 at 9:24 Comment(0)
H
40
TextArea ta = new TextArea();
ta.setText("1234567890");
ta.positionCaret(4);
Hydrogenate answered 30/11, 2011 at 14:5 Comment(3)
positionCaret()... what a confusing name for that method.Giddens
yep, smth like setCaretPosition would be convenientHydrogenate
There's pretty strange behaviour in TextArea, like the down arrow doesn't move down.Tomfoolery
O
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 );
    }
});
Overside answered 22/6, 2015 at 10:57 Comment(0)
E
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.

Emma answered 8/9, 2016 at 5:33 Comment(0)
C
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 .

Chunchung answered 2/8, 2021 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.