17

In Swing, it was trivially easy to style a JLabel using HTML - you simply used the HTML you wanted as the text for the label, and it was rendered appropriately.

In JavaFX this isn't available, but we can set the style of a particular label (or node in general) using the setStyle() method.

However, using this approach it's not obvious how to set part of a label to be a certain style, for instance the equivalent of:

JLabel label = new JLabel("<html>Part of this <b>text is b</b>old and part isn't.</html>");

What would be the easiest way to achieve something like the above?

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • Possibly dublicates [Make portion of a text bold in a JavaFx Label or Text](http://stackoverflow.com/q/12341672/682495) and [Highlighting strings in JavaFX TextArea](http://stackoverflow.com/q/12346009/682495) – Uluk Biy Oct 02 '12 at 16:57

2 Answers2

10

You can try using TextFlow to combine different styled text nodes like

TextFlow textFlow = new TextFlow();

Text first=new Text("Part of this ");
first.setStyle("-fx-font-weight: regular");

Text second=new Text("text is b");
second.setStyle("-fx-font-weight: bold");

Text third=new Text("old and part isn't.");
third.setStyle("-fx-font-weight: regular");

textFlow.getChildren().addAll(first, second, third);
Collins Abitekaniza
  • 4,496
  • 2
  • 28
  • 43
  • yeah, I found that, it may fit the JavaFX internal model better, but it's awful for content providers. I just want to provide the developer I'm working with some rich text content in a configuration file, and have him utilize that content in Java. – Jason S Dec 11 '15 at 19:01
  • 2
    Jason, try googling "JavaFX Markdown", that may or may not assist you in developing a solution. – jewelsea Dec 11 '15 at 22:24
  • How do you get the Label to display the TextFlow? – qwerty Jul 07 '20 at 20:41
8

Pseudo-selectors could have been a work-around but unfortunately most of them are not supported yet - http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#introlimitations. As for Rich Text Support in controls, they will be provided by JavaFX8 - https://bugs.openjdk.java.net/browse/JDK-8091709.

Avik
  • 1,170
  • 10
  • 25