当分布宽度不能为整数时,Hbox 中的按钮宽度不均匀且 hgrow

Buttons in Hbox uneven width with hgrow when distributed width can't be a whole number

我想做一个HBox容器,里面有3个等宽的按钮,但是当父级的宽度不能分成整数部分时,其中一个节点就少了。如果我的 HBox 是 245px,我有 3 个按钮,其中 1 个是 81px,其他是 82px。

问题是在 HBox 顶部我有一个加载圆圈指示器,圆圈位于 HBox 的中心,当中间按钮不居中时,加载圆圈在 HBox 顶部看起来也没有居中。

    HBox root = new HBox();
    root.setFillHeight(true);
    for (int i = 0; i < 3; i++) {
        AnchorPane pane = new AnchorPane();
        HBox.setHgrow(pane, Priority.ALWAYS);
        pane.setMaxHeight(Double.MAX_VALUE);
        root.getChildren().add(pane);
    }
    Scene scene = new Scene(root, 245, 50, Color.TRANSPARENT);
    primaryStage.setScene(scene);
    primaryStage.initStyle(StageStyle.TRANSPARENT);
    primaryStage.show();

    root.getChildren().forEach(node -> {
        AnchorPane pane = ((AnchorPane)node);
        System.out.println(pane.getWidth());
    });

思路是一个登录场景,提交用户名和密码后,服务器正在加载,hbox上面有一个圆形的ProgressIndicator,圆形以它为中心。

中间按钮上方的圆圈看起来没有居中。那么如何在不显式设置按钮宽度的情况下使用布局容器执行此操作。布局是否总是将子级划分为整数?

所以在一些 属性 测试之后,我发现 snapToPixel=false 是正确的选择。

来自关于 snapToPixel 的 oracle 文档 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Region.html

Defines whether this region adjusts position, spacing, and size values of its children to pixel boundaries. This defaults to true, which is generally the expected behavior in order to have crisp user interfaces. A value of false will allow for fractional alignment, which may lead to "fuzzy" looking borders.

我尝试了不同的 px,在我的例子中它的边缘效果很好。

同样,在不触及 snapToPixel 的情况下,我发现列宽为 33.3% 的 GridPane 将 81px 按钮放在中间,hbox 是最后一个子项,因此 GridPane 也对我有用。