如何在javafx中使子自动调整大小(子是Pane,父是VBox)

Rui*_*hou 4 javafx pane vbox

我有2个问题

1.在javafx应用程序中,我想将child(crosshairArea)放在其父级的左上角,宽度和高度也为1/2。认为我可以通过覆盖父函数“layoutChildren”(VBox)来做到这一点,还有其他方法可以做到吗?例如属性绑定?

2.最初VBox会占据整个场景区域,如何使它(重定位)到场景的半底部?

public class Crossh extends Application {

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

    @Override
    public void start(Stage stage) {        
        VBox root = new VBox(5);
        // root.setPadding(new Insets(20,20,20,20));
        root.setStyle("-fx-border-color:red");

        Pane crosshairArea = new Pane();
        crosshairArea.maxWidthProperty().bind(root.widthProperty());
        crosshairArea.setStyle("-fx-border-color:black");       

        root.getChildren().add(crosshairArea);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("Location Crosshair");
        stage.setWidth(900);
        stage.setHeight(700);        
        stage.show();
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ler 5

将 VBox 的最后一个子 vgrow 属性设置为 true。

pane.setVgrow(true);
Run Code Online (Sandbox Code Playgroud)

这将解决问题。

  • `VBox.setVgrow(child, Priority.ALWAYS);` 对我来说效果很好。 (6认同)