javafx change css at runtime

后端 未结 2 911
执念已碎
执念已碎 2020-12-17 16:20

Is it possible to change css for a JavaFX application while it is running?

The effect I am looking for is changing skins or themes at the click of a button.

2条回答
  •  感情败类
    2020-12-17 17:05

    You can also try this piece of code(simple and truly illustrative) :

    • A Container for it: I chose BorderPane.
    • Add a main Scene for your application.
    • A Menu Bar with a set of items depending on the look of your application.
    • And item on the Menu bar.
    BorderPane rootPane = new BorderPane();
    Parent content = FXMLLoader.load(getClass().getResource("sample.fxml"));
    rootPane.setCenter(content);
    Scene scene = new Scene(root, 650, 550, Color.WHITE);
    // Menu bar
    MenuBar menuBar = new MenuBar();
    
    // file menu
    Menu fileMenu = new Menu("_File");
    MenuItem exitItem = new MenuItem("Exit");
    exitItem.setAccelerator(new KeyCodeCombination(KeyCode.X, KeyCombination.SHORTCUT_DOWN));
    exitItem.setOnAction(ae -> Platform.exit());
    
    fileMenu.getItems().add(exitItem);
    menuBar.getMenus().add(fileMenu);
    
    // Look and feel menu
    Menu themeMenu = new Menu("_Theme");
    themeMenu.setMnemonicParsing(true);
    menuBar.getMenus().add(themeMenu);
    rootPane.setTop(menuBar);
    
    
    MenuItem theme1 = new MenuItem("Theme 1");
    theme1.setOnAction(ae -> {
                scene.getStylesheets().clear();
                setUserAgentStylesheet(null);
                scene.getStylesheets()
                        .add(getClass()
                                .getResource("theme1.css")
                                .toExternalForm());
    });
    
    MenuItem theme2 = new MenuItem("Theme 2");
            theme2.setOnAction(ae -> {
                scene.getStylesheets().clear();
                setUserAgentStylesheet(null);
                scene.getStylesheets()
                        .add(getClass()
                                .getResource("theme2.css")
                                .toExternalForm());
    });
    
    
    themeMenu.getItems()
                    .addAll(theme1,
                            theme2);
    
    primaryStage.setScene(scene);
    primaryStage.show();
    

    Supposed that you have your two CSS files in the folder of the class where you will call this code with the corresponding name theme1.css and theme2.css.

    Now you can switch between two themes while your application is running.

提交回复
热议问题