How to set label text color with css in JavaFX?


Overview

In this tutorial, we show you how to set text color with CSS for Label in JavaFX.

set label text color with css in JavaFX

Option 1 - Change color of label text

If you are using JavaFX Scene Builder 2.0, go to the Style of the Label in the Properties section of the Inspector panel. Set -fx-text-fill : #8B008B

Change color of label text

Option 2 - Change color of label text

Using javafx.scene.control.Label.setStyle
package com.jackrutorial;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

public class ExampleController implements Initializable {

    @FXML
    private Label txtLabel;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {

        txtLabel.setStyle("-fx-text-fill: #8B008B;");
    }
}

Option 3 - Change color of label text

Using javafx.scene.control.Label.setTextFill
package com.jackrutorial;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;

public class ExampleController implements Initializable {

    @FXML
    private Label txtLabel;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {

        txtLabel.setTextFill(Color.web("#8B008B"));
    }
}

Option 4 - Change color of label text

Edit Example.fxml file. Add style="-fx-text-fill: #8B008B;" to tag Label
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" fx:id="main" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.jackrutorial.ExampleController">
   <children>
      <Label fx:id="txtLabel" layoutX="109.0" layoutY="139.0" prefHeight="86.0" prefWidth="348.0" style="-fx-text-fill: #8B008B;" text="Hello, Everybody! This is jackrutorial.com" />
   </children>
</AnchorPane>
Previous Post
Next Post

post written by: