【发布时间】:2018-01-26 21:54:23
【问题描述】:
当我遇到以下问题时,我试图使用 GridPane 来布局 JavaFX 阶段。如果我使用适当的约束设置网格并向其添加新实例化的StackPanes,则场景、舞台及其内容的默认大小可确保内容可见:
但是,如果我在将新实例化的 StackPane 添加到 GridPane 之前添加一个指定边框的 JavaFX CSS 样式,那么默认大小的东西似乎完全崩溃了:
我的代码如下:
public static void main(final String[] args) {
Platform.startup(() -> {});
Platform.runLater(() -> {
final GridPane gridPane = new GridPane();
final Scene scene = new Scene(gridPane);
final Stage stage = new Stage();
stage.setScene(scene);
final List<StackPane> panes = new ArrayList<>();
for (int i = 0; i < 4; i++) {
// Create a new pane with a random background color for
// illustration
final StackPane p = createNewPane();
panes.add(p);
// The addition / removal of the following line affects the
// layout.
p.setStyle("-fx-border-width:2px;-fx-border-color:red");
}
for (int r = 0; r < 2; r++) {
final RowConstraints rc = new RowConstraints();
rc.setPercentHeight(50);
gridPane.getRowConstraints().add(rc);
}
for (int c = 0; c < 2; c++) {
final ColumnConstraints cc = new ColumnConstraints();
cc.setPercentWidth(50);
gridPane.getColumnConstraints().add(cc);
}
for (int r = 0, i = 0; r < 2; r++) {
for (int c = 0; c < 2; c++) {
gridPane.add(panes.get(i++), c, r);
}
}
stage.show();
});
}
奇怪的是,如果我在设置场景后将stage.show() 移动到右侧,那么即使使用 CSS,一切都可以正常工作。
谁能帮我理解一下,一,这是否是预期的行为,二,为什么stage.show() 的执行顺序会有所不同?
谢谢!
【问题讨论】:
-
Platform.startUp()方法是 Java 9 的新方法。我以前没见过。调用这个方法是很不寻常的,通常你会扩展Application。 -
@jewelsea 我必须做一个明确的
Platform.startUp(),因为这个问题是在一个混合了遗留Swing 元素和更新的FX 元素的应用程序的上下文中出现的。应用程序本身在 Swing 环境中启动(目前)。