Make a dark mode with JavaFx

Sander B picture Sander B · Mar 7, 2018 · Viewed 8.4k times · Source

I was wondering if there is an easy way to make a dark mode using JavaFx and CSS. I have a MenuBar with a CheckMenuItem called 'Dark mode' and when I click it I want the scene to become dark and the text to become white.

Answer

James_D picture James_D · Mar 7, 2018

It's been a while since I played with "theming" a JavaFX application, but from a while ago I have a CSS file:

.root {
    -fx-base: #3f474f;
    -fx-accent: #e7eff7 ;
    -fx-default-button: #7f878f ;
    -fx-focus-color: #efefef;
    -fx-faint-focus-color: #efefef22;
    -fx-focused-text-base-color : ladder(
            -fx-selection-bar,
            -fx-light-text-color 45%,
            -fx-dark-text-color 46%,
            -fx-dark-text-color 59%,
            -fx-mid-text-color 60%
        );
    -fx-focused-mark-color : -fx-focused-text-base-color ;   

}

.text-input:focused {
    -fx-highlight-text-fill: ladder(
        -fx-highlight-fill,
        -fx-light-text-color 45%,
        -fx-dark-text-color  46%,
        -fx-dark-text-color  59%,
        -fx-mid-text-color   60%
    );
}

If you put this in a file, say dark-theme.css, you can do

checkMenuItem.selectedProperty().addListener((obs, wasSelected, isSelected) -> {
    if (isSelected) {
        scene.getStyleSheets().add("dark-theme.css");
    } else {
        scene.getStyleSheets().remove("dark-theme.css");
    }
});