Make portion of a text bold in a JavaFx Label or Text

In my JavaFx application I need to have a word or two rendered in boldface in the whole sentence. Currently the sentence is rendered as a JavaFx Label but upgrading component also would not allow me set the text as so that I can have the words "Sample" displayed in bold.

String s = "This is a <b>Sample</b> sentence"
Label label = new Label(s);

output

This is a Sample sentence

JavaFx Text also does not allow this. Is there any component where I can have a portion of the text in boldface?

I am not sure if JavaFx WebView is a good idea for rendering many small sentences in a window.


It is possible to use TextFlow container from JavaFX8. Then you can easily add differently styled Text nodes inside it.

TextFlow flow = new TextFlow();

Text text1=new Text("Some Text");
text1.setStyle("-fx-font-weight: bold");

Text text2=new Text("Some Text");
text2.setStyle("-fx-font-weight: regular");

flow.getChildren().addAll(text1, text2);

TextFlow container will automatically wrap content Text nodes.

enter image description here


Since the previous answers did not include FXML code, I'll post an additional one.

As suggested by @Ernisto, you can use a TextFlow that contains Text parts, where each part can be styled differently.

Example FXML file content:

<TextFlow>
  <Text text="Normal text and "/>
  <Text text="bold text and " style="-fx-font-weight: bold"/>
  <Text text="italic text and " style="-fx-font-style: italic"/>
  <Text text="red text." style="-fx-stroke: red"/>
</TextFlow>

Output:

enter image description here


Update: JavaFX 8 provides new control for the rich text: TextFlow


Unfortunately there is no such feature in 2.2, although it may be included into next release.

For now you can try to use next approaches:

  1. HBox with several Label or Text components
  2. WebView
  3. Canvas with several Text components drawn

public class UtilsDialog {

    private static final String TAG = "UtilsDialog";

    private static boolean sIsShowing = false;

    public static void showDialogShowError(String title, String msg, String defaultStyle,
                                           @Nullable String customStyle, String... styledWords) {
        if (sIsShowing) return;

        Stage dialogStage = new Stage(StageStyle.UTILITY);
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        dialogStage.setWidth(400);
        dialogStage.setHeight(220);

        BorderPane borderPane = new BorderPane();

        borderPane.setPadding(new Insets(15));
        borderPane.setPrefWidth(Integer.MAX_VALUE);
        borderPane.setPrefHeight(Integer.MAX_VALUE);

        Scene scene = new Scene(borderPane);
        dialogStage.setScene(scene);
        sIsShowing = true;
        dialogStage.show();
        UtilsGui.closeOnEsc(borderPane, scene);
        scene.addEventHandler(KeyEvent.KEY_PRESSED, t -> {
            if (t.getCode() == KeyCode.ESCAPE) {
                sIsShowing = false;
            }
        });

        // Top
        Text textTitle = new Text(title);
        textTitle.setStyle("-fx-font-size: 18px;");

        HBox hBoxTop = new HBox(10);
        hBoxTop.getChildren().addAll(textTitle);
        borderPane.setTop(hBoxTop);

        // Center
        TextFlow textFlow = new TextFlow();
        List<String> words = Arrays.asList(msg.split(" "));
        List<String> styledWordsList = Arrays.asList(styledWords);
        for (String word : words) {
            Text tmpWord = new Text(word);
            if (styledWordsList.contains(word
                    .replace(".", "")
                    .replace(",", "")
                    .replace("?", "")
                    .replace("!", "")
                    .replace(";", "")
                    .replace("\n", "")
            )) {

                tmpWord.setStyle(customStyle);
            } else {
                if (defaultStyle == null) {
                    tmpWord.setStyle("");
                } else {
                    tmpWord.setStyle(defaultStyle);
                }
            }
            tmpWord.setText(tmpWord.getText());
            textFlow.getChildren().add(tmpWord);
            textFlow.getChildren().add(new Text(" "));
        }
        Text textMsg = new Text(msg);
        textMsg.setStyle("-fx-font-size: 14px;");
        HBox hBoxInputPane = new HBox(10);
        hBoxInputPane.setAlignment(Pos.CENTER);

        VBox vBoxCenter = new VBox(10);
        vBoxCenter.setPadding(new Insets(25, 0, 15, 0));
        vBoxCenter.getChildren().addAll(textFlow);
        borderPane.setCenter(vBoxCenter);

        JFXButton btnOk = new JFXButton("OK");
        btnOk.setAlignment(Pos.CENTER_RIGHT);
        btnOk.setStyle("-fx-text-fill: WHITE; -fx-background-color: #5264AE; -fx-font-size: 14px;");
        btnOk.setOnAction(event -> {
            sIsShowing = false;
            dialogStage.close();
        });

        // Bottom
        HBox hBoxBottom = new HBox();
        final Pane spacer = new Pane();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        hBoxBottom.getChildren().addAll(spacer, btnOk);
        borderPane.setBottom(hBoxBottom);

        // store on close
        dialogStage.setOnCloseRequest(event -> sIsShowing = false);
    }
}

call:

UtilsDialog.showDialogShowError("Test", "This is the message to show. Does it work?",
                null, "-fx-font-weight: bold", "This", "message", "show");