Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX HTML styling (or equivalent) labels

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?

like image 270
Michael Berry Avatar asked Oct 02 '12 16:10

Michael Berry


People also ask

Does JavaFX use HTML and CSS?

The package javafx. css contains the classes that are used to apply CSS for JavaFX applications. A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding elements in your document. Selector − A selector is an HTML tag at which a style will be applied.

What is the difference between text and Label in JavaFX?

A Text is a geometric shape (like a Rectangle or a Circle), while Label is a UI control (like a Button or a CheckBox). In Swing, geometric shapes were restricted to the painting mechanism, while in JavaFX they can be used in more generic ways. And you can use a Text clipping, giving the node shape by the text.

How do I change a Label in JavaFX?

You can change the text of a label using its setText() method. This can be done while the application is running. Here is an example of setting the text of a JavaFX Label: label.


1 Answers

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);
like image 192
Collins Abitekaniza Avatar answered Sep 19 '22 04:09

Collins Abitekaniza