You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GridPane中的Label始终完全可见,仅TextField收缩?

解决方案

要实现Label始终完全可见、仅TextField收缩的需求,你需要调整GridPane的列约束,确保Label所在列的最小宽度匹配其内容宽度,避免被压缩。具体修改如下:

关键调整点

  • 给Label对应的列约束设置setMinWidth(ColumnConstraints.USE_PREF_SIZE),强制列的最小宽度等于Label的首选内容宽度,从根源上防止Label被截断。
  • 保持TextField列的Hgrow为Priority.ALWAYS,让它们占据窗口剩余空间,同时设置合理的最小宽度保证组件可用性。

修改后的完整代码

public class NewMain extends Application {

    @Override
    public void start(Stage stage) {
        GridPane gridPane = new GridPane();
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        gridPane.setPadding(new Insets(10));

        Label label1 = new Label("Label AAAAA BBBBB:");
        TextField textField1 = new TextField();
        textField1.setMinWidth(50); // 设置合理最小宽度,避免组件过窄
        GridPane.setHgrow(textField1, Priority.ALWAYS);
        
        Label label2 = new Label("Label CCCCCC DDDDDD:");
        TextField textField2 = new TextField();
        textField2.setMinWidth(50);
        GridPane.setHgrow(textField2, Priority.ALWAYS);

        gridPane.add(label1, 0, 0);
        gridPane.add(textField1, 1, 0);
        gridPane.add(label2, 2, 0);
        gridPane.add(textField2, 3, 0);

        // Label列约束:最小宽度匹配内容首选宽度,不允许扩展
        ColumnConstraints labelColumn = new ColumnConstraints();
        labelColumn.setMinWidth(ColumnConstraints.USE_PREF_SIZE);
        labelColumn.setHgrow(Priority.NEVER);

        // TextField列约束:自动填充剩余空间,保留最小宽度
        ColumnConstraints textFieldColumn = new ColumnConstraints();
        textFieldColumn.setMinWidth(50);
        textFieldColumn.setHgrow(Priority.ALWAYS);

        gridPane.getColumnConstraints().addAll(
            labelColumn, textFieldColumn,
            labelColumn, textFieldColumn
        );

        Scene scene = new Scene(gridPane, 600, 100);
        stage.setTitle("GridPane Single Row Test");
        stage.setScene(scene);
        stage.show();
    }

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

效果说明

修改后,窗口宽度缩小时,Label所在列会固定保持自身内容的宽度,不会出现截断;TextField会自动收缩到设置的最小宽度,优先保证Label的完整可见性。

内容的提问来源于stack exchange,提问作者SilverCube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:02:42