JavaFX AnchorPane无法正常工作

时间:2015-09-26 10:13:03

标签: java javafx

我试图使用AnchorPane来锚定两个矩形,虽然由于某些原因这似乎不起作用:

普通屏幕

enter image description here

最大化屏幕

enter image description here 2 这是我的代码:

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

    @Override
    public void start(Stage MainStage) throws Exception {

        // Setup window
        MainStage.setTitle("Minx IDE - Version 1.0.0");
        Group Root = new Group();
        Scene MainScene = new Scene(Root, 1000, 600, Color.rgb(44, 62, 80));
        MainStage.setScene(MainScene);
        MainStage.show();

        // Setup window components
        // Info box
        Rectangle InfoBox = RectangleBuilder.create()
                .x(700)
                .y(0)
                .width(300)
                .height(600)
                .fill(Color.rgb(149, 165, 166))
                .build();

        // Save bar
        Rectangle SaveBar = RectangleBuilder.create()
                .x(0)
                .y(575)
                .width(700)
                .height(25)
                .fill(Color.rgb(52, 152, 219))
                .build();

        AnchorPane Anchor = new AnchorPane(InfoBox, SaveBar);
        AnchorPane.setBottomAnchor(SaveBar, 0.0);
        AnchorPane.setLeftAnchor(SaveBar, 0.0);
        AnchorPane.setTopAnchor(InfoBox, 0.0);
        AnchorPane.setRightAnchor(InfoBox, 0.0);

        // Add components to root and anchor
        Root.getChildren().addAll(InfoBox, SaveBar);

    }

请告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

考虑到无论屏幕大小如何都需要将矩形锚定在各自的位置,您需要删除Group作为场景的根,并使AnchorPane成为场景的根。

Group布局不会自动调整大小并保留其子项的大小。

创建以anchorPane为根的场景将解决您的问题,因为它会根据空间的可用性自行调整大小。

Scene mainScene = new Scene(anchorPane, 1000, 600, Color.WHITE);

注意:

    JavaFX 8中不推荐使用
  1. RectangleBuilder,因此请避免使用它。
  2. 在命名变量时尝试使用CamelCase。它是Java中遵循的默认命名约定。
相关问题