Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX change the font color of text in a tab

Tags:

java

css

javafx

I would like to dynamically change the color of the text in the tab label of a TabPane.

In SceneBuilder I've given the tab a name of randomTab.

In my code, I have the following:

    if (randomEnabled)
        randomTab.setStyle("-fx-color:Green;");
    else
        randomTab.setStyle("-fx-color:Black;");

However, this doesn't change the color of the text, it changes the color of the background of the tab's label.

I've tried "-fx-text-fill:Green" instead, as well as "-fx-foreground-color:Green", but neither of those have any effect.

like image 530
skrilmps Avatar asked Sep 14 '25 11:09

skrilmps


1 Answers

Labels inside the tab header, by default, use the "looked-up color" -fx-text-base-color defined in the default stylesheet modena.css. So a quick-and-dirty approach is just to override that color definition:

randomTab.setStyle("-fx-text-base-color: green;");

The problem with this approach is that anything else in the tab (i.e. not in the tab header) that uses -fx-text-base-color as its text fill will also change text color. Most controls actually use -fx-text-background-color as the text (foreground!) color, so you might get away with this simple approach. (Thanks to jewelsea, whose comments led me to the correct version of this approach.)

Probably a more robust approach is to define your own "looked-up color" for the text fill in the tab, and then change its value for a specific tab in code.

In your external CSS file, add

.root {
    -tab-text-color: -fx-text-base-color ;
}

.tab-label {
    -fx-text-fill: -tab-text-color ;
}

Now to change the value of -tab-text-color for a specific tab, do

randomTab.setStyle("-tab-text-color: green;");

Here's a SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class TabStyleTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        TabPane tabPane = new TabPane();
        Tab tab1 = new Tab("Tab 1");
        tab1.setContent(new StackPane(new Label("Tab 1")));
        tab1.setStyle("-tab-text-color: green;");
        Tab tab2 = new Tab("Tab 2");
        tab2.setContent(new StackPane(new Label("Tab 2")));
        tabPane.getTabs().addAll(tab1, tab2);
        Scene scene = new Scene(tabPane, 600, 600) ;
        scene.getStylesheets().add("style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

where style.css is

.root {
    -tab-text-color: -fx-text-base-color ;
}

.tab-label {
    -fx-text-fill: -tab-text-color ;
}

Giving

enter image description here

like image 74
James_D Avatar answered Sep 17 '25 00:09

James_D