package felipe; import java.lang.reflect.Method; import com.sun.javafx.scene.text.HitInfo; import com.sun.javafx.scene.text.TextLayout; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Stage; public class TextFlowHitTest extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Text text1 = new Text("Lorem ipsum dolor sit amet, "); Text text2 = new Text("consectetur adipisicing elit, "); Text text3 = new Text("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); text1.setFill(Color.RED); text2.setFill(Color.GREEN); text3.setFill(Color.BLUE); TextFlow textFlow = new TextFlow(text1, text2, text3); Method m = TextFlow.class.getDeclaredMethod("getTextLayout"); m.setAccessible(true); TextLayout layout = (TextLayout)m.invoke(textFlow); Scene scene = new Scene(textFlow, 300, 300); scene.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler () { @Override public void handle(MouseEvent event) { System.out.println(new Point2D(event.getX(), event.getY())); HitInfo hit = layout.getHitInfo((float)event.getX(), (float)event.getY()); ObservableList nodes = textFlow.getChildren(); int start = 0; for (Node n : nodes) { Text text = (Text)n; String string = text.getText(); if (start + string.length() > hit.getCharIndex()) { System.out.println("Click on node " + text.getFill()); System.out.println("Node relative offset " + (hit.getCharIndex() - start)); System.out.println("TextFlow relative hit " + hit); break; } start += string.length(); } } }); stage.setScene(scene); stage.show(); } }