我需要为自己的任务创建一个chat-simulating JavaFX应用程序(没有Web功能,只有两个文本字段用于输入,两个文本区域用于输出)。我的文本字段旁边需要有一个“发送”按钮。我无法在启动时不“挤压”按钮的情况下使文本字段填满窗口的宽度,这与swing的bo​​xLayout相似吗?

我将字段的宽度与父窗格的宽度绑定在一起,减去按钮的宽度和窗格的间距,然后在开始调整窗口大小后就可以使用,但是当应用程序首次启动时,按钮的文本并不完全可见。

public void start(Stage stage_main) throws Exception {
        //Pane creation and nesting:
        HBox pane_main = new HBox();
        Scene scene_main = new Scene(pane_main, 480, 360);
        BorderPane pane_left_parent = new BorderPane();
        BorderPane pane_right_parent = new BorderPane();
        HBox pane_left_bottom = new HBox();
        HBox pane_right_bottom = new HBox();
        pane_main.getChildren().addAll(pane_left_parent, pane_right_parent); //Focusing only on the left pane for now for testing.
        pane_left_parent.setBottom(pane_left_bottom);

        //Contents creation and nesting:
        TextArea textA_left = new TextArea("Testing...");
        Button button_left = new Button("Send");
        TextField textF_left = new TextField("Test input...");
        textF_left.prefWidthProperty().bind(pane_left_bottom.widthProperty().subtract(button_left.widthProperty()).subtract(pane_left_bottom.spacingProperty()));

        //Placing contents in panes:
        pane_left_parent.setCenter(textA_left);
        pane_left_bottom.setSpacing(3);
        pane_left_bottom.getChildren().addAll(textF_left, button_left);

        //Finishing up:
        stage_main.setScene(scene_main);
        stage_main.show();
    }

是否有任何方法可以使按钮在启动时就已经具有“最佳”大小,而无需像挥杆一样手动设置任何像素宽度?

分析解答

不要将prefWidth绑定到父对象。如果希望HBox的子级水平增长,则可以在其上设置hgrow约束:

HBox.setHgrow(theChild, Priority.ALWAYS);

然后让HBox处理子节点的大小和位置。正如您所指出的,为了防止ButtonHBox更改大小时收缩,您需要设置minWidth。但是,您应该使用:

button.setMinWidth(Region.USE_PREF_SIZE);

如果使用getWidth(),则可能在Button实际具有non-zero宽度之前意外地调用它。另外,使用USE_PREF_SIZE意味着minWidth将与prefWidth一起保留up-to-date(如果出于任何原因进行了更改)。


一些链接: