import javafx.application.*; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.scene.text.*; import javafx.stage.*; public class Highlight extends Application { public static void main(String[] args) { launch(args); } static final String str1 = "This sentence is not highlighted."; static final String str2 = "This sentence is highlighted in blue."; static final String str3 = "This sentence is highlighted in red."; @Override public void start(Stage stage) { Text text = new Text(str1 + " " + str2 + " " + str1 + " " + str3 + " " + str1); text.setWrappingWidth(100); HighlightPane highlightPane = new HighlightPane(text); highlightPane.highlight(str2, Color.LIGHTBLUE); highlightPane.highlight(str3, Color.RED); stage.setScene(new Scene(highlightPane)); stage.show(); } static class HighlightPane extends StackPane { private Text text; private Group selectionHighlightGroup = new Group(); public HighlightPane(Text text) { this.text = text; getChildren().add(selectionHighlightGroup); getChildren().add(text); } public void highlight(String highlightStr, Color color) { String str = text.getText(); int index = -1; while ((index = str.indexOf(highlightStr, index + 1)) >= 0) { text.setImpl_selectionStart(index); text.setImpl_selectionEnd(index + highlightStr.length()); PathElement[] selectionShape = text.getImpl_selectionShape(); if (selectionShape != null) { Path selectionHighlightPath = new Path(); selectionHighlightPath.setManaged(false); selectionHighlightPath.setStroke(null); selectionHighlightPath.getElements().addAll(selectionShape); selectionHighlightGroup.getChildren().add(selectionHighlightPath); selectionHighlightPath.setFill(color); } } } @Override public void layoutChildren() { super.layoutChildren(); selectionHighlightGroup.setLayoutX(text.getLayoutX()); selectionHighlightGroup.setLayoutY(text.getLayoutY()); } } }