Search code examples
cssjavafxbackgroundinlinemaximize-window

Javafx: Change in-line css style during runtime


I am attempting to change the background image of a pane when the application is maximized. My background is set using in-line css. I've set up two different variables for the styling and an if statement. However, I'm not having any luck getting it to change the styling.

String cssStyle = "-fx-background-image: url(\'file:images/poker_table.png\');" +
                 "-fx-background-position: center center;" +
                 "-fx-background-radius: 15;" + // ************* For rounded corners
                 "-fx-background-size: 100% 100%;";
String cssStyle2 = "-fx-background-image: url(\'file:images/poker_table.jpg\');" +
                  "-fx-background-position: center center;" +
                  "-fx-background-radius: 15;" +
                  "-fx-background-size: 100% 100%;";
if (!primaryStage.isMaximized())
{   gameScreen.setStyle(cssStyle);
}
else
{   gameScreen.setStyle(cssStyle2);
}


Solution

  • Simply add a listener to the stage's maximizedProperty(). Properties and listeners are a fundamental part of the JavaFX API: you can read about them in the standard documentation, or any good JavaFX tutorial.

    primaryStage.maximizedProperty().addListener((obs, wasMaximized, isNowMaximized) -> {
        if (isNowMaximized) {
            gameScreen.setStyle(cssStyle2);
        } else {
            gameScreen.setStyle(cssStyle);
        }
    });
    

    You probably also need to set the appropriate style immediately, using the code you already have.

    You can use a binding instead, if you prefer:

    gameScreen.styleProperty().bind(Bindings.createStringBinding(
        () -> primaryStage.isMaximized() ? cssStyle2 : cssStyle,
        primaryStage.maximizedProperty()
    );
    

    The binding can replace the code you already have; it will both be applied immediately and any time the maxmizedProperty changes.