JavaFX HTML styling (or equivalent) labels

2019-06-15 01:12发布

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?

2条回答
放荡不羁爱自由
2楼-- · 2019-06-15 01:45

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);
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-06-15 01:52

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.

查看更多
登录 后发表回答