I'm trying to change the background image of a pane when the application is maximized. My background is set using inline css. I set up two different variables and an if statement for the style. However, I'm having no luck getting it to change style.
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); }
P粉4125335252024-04-07 19:47:58
Just add a listener to the Stage's maximizedProperty()
. Properties and listeners are a fundamental part of the JavaFX API: you can find them in the Standards Documentation, or any good JavaFX tutorial.
primaryStage.maximizedProperty().addListener((obs, wasMaximized, isNowMaximized) -> { if (isNowMaximized) { gameScreen.setStyle(cssStyle2); } else { gameScreen.setStyle(cssStyle); } });
You may also want to set appropriate styles immediately using existing code.
You can also use binding if you prefer:
gameScreen.styleProperty().bind(Bindings.createStringBinding( () -> primaryStage.isMaximized() ? cssStyle2 : cssStyle, primaryStage.maximizedProperty() );
Binding replaces your existing code; it is applied immediately and when maxmizedProperty
changes.