Is it possible to get the caret position (an int
) at a screen coordinate (2 double
) in JavaFX TextArea
?
JavaFX TextArea get caret position from coordinate
5.2k views Asked by Tengyu Liu At
3
There are 3 answers
0
On
import com.sun.javafx.scene.control.skin.TextAreaSkin;
import com.sun.javafx.scene.text.HitInfo;
/****************************************************/
TextAreaSkin skin = (TextAreaSkin) target.getSkin();
HitInfo mouseHit = skin.getIndex(e.getX(), e.getY());
// Now you can position caret
skin.positionCaret(mouseHit, false, false);
// And/or get insertion index
int insertionPoint = mouseHit.getInsertionIndex();
For TextArea
this method is equivalent to Roland’s answer. The practical difference of this method is its applicability to TextField
(another subclass of TextInputControl
):
TextFieldSkin skin = (TextFieldSkin) target.getSkin();
HitInfo mouseHit = skin.getIndex(e.getX(), e.getY());
skin.positionCaret(mouseHit, false);
int insertionPoint = mouseHit.getInsertionIndex();
Unfortunately, TextFieldSkin
does not override the getInsertionPoint(...)
and the parent's implementation returns 0 so the alternative solution does not work here.
Regarding Java 9, both Roland’s and my answers will still work.
The packages com.sun.javafx.scene.control.skin
and com.sun.javafx.scene.text
(where HitInfo
class is located) are moving to the public API in Java 9. Their locations will be javafx.scene.control.skin
and javafx.scene.text
, respectively. See Javadocs for JavaFX 9 here: http://download.java.net/java/jdk9/jfxdocs/index.html
You can use the getInsertionPoint method of the TextAreaSkin in your drag handler:
However, the skin class is in com.sun.javafx.*, so with Java 9 coming out you'll probably have to do things differently then. Nobody knows what they'll break or what they provide as replacement. However, with Java 8 it works (for now).
Full example in which you can drag a Label's text into any position in the TextArea: