Javafx - change Theme (CSS) on active window

762 views Asked by At

I want a Button that allows me to switch between Dark/Light-mode. But I have the problem If I switch, the active windows will not change their Style.

First of the Code snippets to easy recreate the problem. For Maven projects starter class:

package testapp;

//This Class is Required in mavenproject to Start the Application

public class GUIStarter {
    public static void main(final String[] args) {
        try{
            TestApp.main(args);
        }catch (Exception e){
            System.out.println("GUIStarter Errror:\n"+e);
        }
    }
}

The primary Window class:

public class TestApp extends Application {
    //stylepaths
    public static String mainLightModePath = ".\\style_lightmode.css";
    public static String mainDarkModePath = ".\\style-Darkmode.css";
    public static boolean isItDarkmode = true;

    public static void toggleMode(){
        if(isItDarkmode){
            isItDarkmode  = false;
        }else if(!isItDarkmode){
            isItDarkmode = true;
        }

    }

    //This is required to get the primary Stage in other Stages (Controllers)
    private static Stage pStage;

    public static Stage getPrimaryStage() {
        return pStage;
    }

    private void setPrimaryStage(Stage pStage) {
        TestApp.pStage = pStage;
    }

    public void setPrimaryWindow(Stage primaryStage){

        try{
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));
            
            Parent root = (Parent) fxmlLoader.load();
            Scene scene = new Scene(root);

            primaryStage.setTitle("TestApp");

            //scene.setMoveControl(titleBar);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e){
            e.printStackTrace();
        }
        
    }

    //Start of Application
    @Override
    public void start(Stage primaryStage) {
        setPrimaryStage(primaryStage);
        pStage = primaryStage;
        setPrimaryWindow(primaryStage);
    }

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

The maincontroller Class:

public class Mainframe {
        public static Timeline time;

        @FXML
        public void options(ActionEvent event){
            try{ 
                TestApp.toggleMode();
                Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
                Stage changer = TestApp.getPrimaryStage();
                stage.close();
                changer.hide();
                //My idea was to initialize again and load the styles in that way again but does not change anything
                FXMLLoader loader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));
                loader.load();
                Mainframe ctrl = loader.getController();
                ctrl.initialize();
                changer.show();
                
                
            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());
        }else if(!TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }
    
}

Mainframe.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>

<BorderPane fx:id="primaryparent" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="0.0" minWidth="0.0" prefHeight="224.0" prefWidth="515.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="testapp.Mainframe">
   <center>
      <AnchorPane prefHeight="200.0" prefWidth="200.0" styleClass="rootBackground" BorderPane.alignment="CENTER">
         <children>
            <Button fx:id="setDarkModeButton" layoutX="175.0" layoutY="99.0" mnemonicParsing="false" onAction="#options" styleClass="settingsButton" text="toggle Dark/LightMode">
               <font>
                  <Font name="Arial" size="13.0" />
               </font>
               <padding>
                  <Insets bottom="5.0" left="17.0" right="17.0" top="5.0" />
               </padding>
            </Button>
         </children>
      </AnchorPane>
   </center>
</BorderPane>


Before I just overwrote the "style.css" file and used .stop() & .show(). This worked fine. But it can get complicated the more css-files you have and after it is packed into a .jar file it doesn't work anymore.

I hope anyone can help me. Because now I have really no Idea...

UPDATE: I want to control it from another controller:

package testapp;
public class Mainframe {
        public static Timeline time;

        @FXML Button setDarkModeButton;

        @FXML
        public void options(ActionEvent event){
            try{ 
                try{
                    Stage secSTAGE = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader(TestApp.class.getResource("Mainframe2.fxml"));
                    Parent root = (Parent) fxmlLoader.load();
                    Scene scene = new Scene(root);
        
                    secSTAGE.setTitle("TestAppw2");
        
                    //scene.setMoveControl(titleBar);
                    secSTAGE.setScene(scene);
                    secSTAGE.show();
                } catch (Exception e){
                    e.printStackTrace();
                }
                
                
            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }
    
}

public class Mainframe2 {
        public static Timeline time;

        @FXML Button setDarkModeButton;

        @FXML
        public void options(ActionEvent event){
            try{ 
                TestApp.toggleMode();
                Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();

                FXMLLoader loader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));
                Parent root = (Parent) loader.load();
                Mainframe ctrl = loader.getController();

                //setDarkModeButton.getStylesheets().set(0, "style_lightmode.css");
                if(TestApp.isItDarkmode){
                    root.getStylesheets().set(0, Mainframe.class.getResource(TestApp.mainDarkModePath).toString());
                }else{
                    root.getStylesheets().set(0, Mainframe.class.getResource(TestApp.mainLightModePath).toString());
                }            
            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());

        }else if(!TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }
    
}

2

There are 2 answers

11
Giovanni Contreras On BEST ANSWER

Css file can be changed on the run without reloading or setting a new stage

replacing the styleSheet with set() method for observableList

css file javafx

App.java

public class App extends Application {

    @Override
    public void start(Stage stage) {
        
        Button button = new Button("change");
        button.setOnAction(e ->button.getScene().getStylesheets().set(0, "1.css"));
        
        Button button1 = new Button("default");
        button1.setOnAction(e ->button.getScene().getStylesheets().set(0, "0.css"));
        HBox hBox = new HBox(button,button1);
        
        
        AnchorPane anchorPane =new AnchorPane(hBox);
        anchorPane.getStyleClass().add("pane");
        
        var scene = new Scene(anchorPane, 640, 480);
        scene.getStylesheets().add("0.css");
        stage.setScene(scene);
        stage.show();
    }

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

}

0.css

.pane{
    -fx-background-color:cyan;
    
}

1.css

.pane{
    -fx-background-color:orange;
    
    }
0
Muddyblack k On

Seen that kind of nobody is interested in my question. It is not what I wanted but as long as nobody has a better solution:

You can close the old stage and create a new one with the new Theme-style.

So in the TestApp.class the setPrimaryWindow() method must be set public and static. So you can't use .getClass() and the pStage must be set to the new Stage in the setPrimaryWindow():

public static void setPrimaryWindow(Stage primaryStage){

    try{
        pStage = primaryStage;
        FXMLLoader fxmlLoader = new FXMLLoader(TestApp.class.getResource("Mainframe.fxml"));
        
        Parent root = (Parent) fxmlLoader.load();
        Scene scene = new Scene(root);

        primaryStage.setTitle("TestApp");

        //scene.setMoveControl(titleBar);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (Exception e){
        e.printStackTrace();
    }
    
}

@Override
public void start(Stage primaryStage) {
    setPrimaryStage(primaryStage);
    setPrimaryWindow(primaryStage);
}

In the options maincontroller.class you just close() the old window and call setPrimaryWindow():

@FXML
public void options(ActionEvent event){
    try{ 
        TestApp.toggleMode();
        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
        Stage changer = TestApp.getPrimaryStage();
        stage.close();
        changer.close();

        //create new Window on Theme switch
        Stage nStage = new Stage();
        TestApp.setPrimaryWindow(nStage);
        
        
    }catch (Exception e) {
        System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
    e.printStackTrace();
    }
}