AnchorPane 内的 GridPane

GridPane inside AnchorPane

我在 AnchorPane 上放了一个 Gridpane,我的 Gridpane 有一组 TextField、Label 和 Buttons,我想把它放在 Anchorpane 中,但我的 GridPane 只是粘在 AnchorPane 的左上角,我已经为 GridPane 设置一个 setTopanchor 等...但它不适用于我希望它放在中心的 Anchorpane。这是样本。是否有任何遗漏,只是不适用于 AnchorPane? tnx 我会等你的帮助。

如果我答对了你的问题并且你想在 AnchorPane 中居中 GridPane,你可以在每次 AnchorPane 宽度或高度变化时尝试这样的事情 (anchorPane.widthProperty().addListener()):

    double x = (anchorPane.getWidth() - GRID_SIZE) / 2;
    double y = (anchorPane.getHeight() - GRID_SIZE) / 2;

    AnchorPane.setRightAnchor(grid, x);
    AnchorPane.setTopAnchor(grid, y);
    AnchorPane.setLeftAnchor(grid, x);
    AnchorPane.setBottomAnchor(grid, y);

基本上,你需要计算每边的偏移量并设置一个锚点。

下面是一些 StackPane 和 AncorPane 的演示代码: https://github.com/varren/JavaFX-Center-GridPane-in-other-Pane/tree/master/src/sample

但是如果你只是想让你的网格占据完整的 AnchorPane 大小,你可以简单地设置

    AnchorPane.setRightAnchor(grid, .0);
    AnchorPane.setTopAnchor(grid, .0);
    AnchorPane.setLeftAnchor(grid, .0);
    AnchorPane.setBottomAnchor(grid, .0);

并且不需要监听 AnchorPane 大小的变化。