JavaFX: Dynamically Colored Window with CSS

前端 未结 3 1476
长发绾君心
长发绾君心 2021-01-24 02:19

I am attempting to create a Pane object with JavaFX that has three different colors: A color for the background, a color for the text, and a color for the buttons. Each of these

3条回答
  •  渐次进展
    2021-01-24 02:45

    You're lucky, since the only difference are colors. You can use lookedup colors for this puropse: Use my-color-name: ; rules for the node itself or for one of the ancestors. This allows you to specify those values inline css and use them in your CSS stylesheet:

    @Override
    public void start(Stage primaryStage) {
        HBox hBox = new HBox();
        hBox.setMaxHeight(Region.USE_PREF_SIZE);
        hBox.getStyleClass().add("box");
    
        StackPane root = new StackPane(hBox);
    
        Stream.of("red", "green", "blue").map(c -> {
            Button b = new Button(c);
            b.setOnAction(evt -> {
                root.setStyle("-my-background:" + c);
            });
            return b;
        }).forEach(hBox.getChildren()::add);
    
        Scene scene = new Scene(root, 500, 500);
        scene.getStylesheets().add(getClass().getResource("/path/to/my/style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    CSS stlyesheet

    .box {
        -fx-background-color: -my-background;
    }
    

    You can specify multiple colors this way, e.g.

    root.setStyle("-my-color: red; -some-other-color: brown; -color-3: yellow;");
    

提交回复
热议问题