Warm tip: This article is reproduced from stackoverflow.com, please click
css javafx

Add red asterisk to the beginning of text to a javafx label

发布于 2020-03-29 21:03:02

I have a scene (created in SceneBuilder) with a number of labels some of which I want to show as required fields by adding a red asterisk at the beginning of the label text. I cannot see how to do this in SceneBuilder. Is there a way of doing this using CSS.

Below is the label snippet form the FXML file:

            <Label fx:id="lblFirstName" alignment="CENTER_RIGHT" prefHeight="17.0" prefWidth="295.0" text="First Name:" GridPane.columnIndex="1" GridPane.rowIndex="2">
               <padding>
                  <Insets right="10.0" />
               </padding>
            </Label>

Everything I have found so far relates to HTML files.

Questioner
Yasterfari
Viewed
98
Amarildo 2020-01-31 20:07

Slaw suggestion is good, but I would suggest another way using validation.
Note that this method requires ControlsFX library and some code in your controller (can't be done in css as you mentioned).
In your controller class create a validator:

ValidationSupport validationSupport = new ValidationSupport();

Add validation (as a required field) to your node (TextField in this example) inside initialize method:

validationSupport.registerValidator(myTextField, Validator.createEmptyValidator("Field is required"));

Now when you run your application the required TextField will look like this: validated-text-field

If the focus is lost from TextField and it doesn't have any text in it, it will show a red X like this: validation-didnt-pass