父母在JavaFX中的孤儿窗格上具有样式的未样式化子项

时间:2018-07-25 15:22:12

标签: javafx javafx-8 javafx-css

我以简单的样式(例如“ setStyle(”-fx-background-color:yellow;“)”)将子对象添加到孤立的HBox中,然后,当我将孤立的HBox作为子对象添加到窗格中时,该HBox的子对象将不再设置样式。如何使孤儿HBox的子代正确呈现?

示例代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    private int num = 0;
    private HBox flowPane = new HBox();

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();
        Scene scene = new Scene(root, 400, 100);
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(scene);
        primaryStage.show();

        flowPane.setStyle("-fx-background-color: yellow;"); // without this line all is fine
        flowPane.setSpacing(2);

        HBox content = new HBox();
        Button show = new Button("show") {{
            setOnMouseClicked(e -> content.getChildren().setAll(flowPane));
        }};
        Button hide = new Button("hide") {{
            setOnMouseClicked(e -> content.getChildren().clear());
        }};
        Button add = new Button("add") {{
            setOnMouseClicked(e -> flowPane.getChildren().add(createNew()));
        }};
        Button reapply = new Button("reapply") {{
            setOnMouseClicked(e -> content.impl_reapplyCSS());
        }};
        root.getChildren().setAll(new HBox(show, hide, add, reapply), content);
    }

    private StackPane createNew() {
        return new StackPane() {{
            setStyle("-fx-background-color: red; -fx-min-height: 50px; -fx-max-height: 50px; -fx-min-width: 50px; -fx-max-width: 50px;");
            getChildren().add(new Label("" + ++num));
        }};
    }
}

在此队列中单击按钮后:显示,添加,隐藏,添加,显示,添加结果将如下所示:

enter image description here

为什么此图片上的2个框未设置样式? :(

0 个答案:

没有答案
相关问题