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

如何让GridPane内的Label实现文本换行并完整显示段落

解决GridPane中Label文本截断问题

问题分析

你已经给Label设置了wrapText=true但文本仍只显示第一句就被截断,核心原因是固定了Label的prefHeight为230,同时GridPane对应行的高度没有根据文本内容自动调整,导致超出固定高度的文本被裁剪。另外GridPane.setHalignment仅控制组件在单元格内的水平对齐,你用setAlignment(Pos.CENTER)实现文本在Label内部居中的设置是正确的,但需要确保Label有足够空间展示多行内容。

解决方案

  1. 移除Label的固定prefHeight,让高度随文本内容自动扩展
  2. 给GridPane添加行约束,指定对应行可自动调整高度
  3. 保留wrapText=true和文本居中设置,同时确保Label宽度约束合理

修改后的代码

ImageView imgView = new ImageView(TRANSITION);
ImageView backView = new ImageView(GameMenu.BUTTON);
ImageView ins1View = new ImageView(INS1);
ImageView ins2View = new ImageView(INS2);
ImageView ins3View = new ImageView(INS3);

Label firstLbl = new Label("Use WASD keys to move the character. Sample sentence sample sample sample sample. Sample sample sample sample.");
try {
    firstLbl.setFont(Font.loadFont(new FileInputStream(GameMenu.LIGHTFONT_PATH),15));
} catch (FileNotFoundException e1) {
    Font font = Font.font("Arial Black", FontWeight.BOLD, 20);
    firstLbl.setFont(font);
}
firstLbl.setTextFill(Color.BLACK);
firstLbl.setPrefWidth(230);
// 移除固定高度限制,让Label随内容自动调整高度
firstLbl.setWrapText(true);
firstLbl.setAlignment(Pos.CENTER);
// 允许Label高度无上限,确保能容纳所有文本
firstLbl.setMaxHeight(Double.MAX_VALUE);

setLayoutX(0);
setLayoutY(0);

// 添加行约束:第1行(索引从0开始)允许自动扩展高度
RowConstraints row1 = new RowConstraints();
row1.setVgrow(Priority.ALWAYS);
grid.getRowConstraints().addAll(new RowConstraints(), row1);

grid.add(ins1View, 0, 0, 1, 1);
GridPane.setHalignment(ins1View, HPos.CENTER);
grid.add(firstLbl, 0, 1, 1, 1);
GridPane.setHalignment(firstLbl, HPos.CENTER);
// 让Label在单元格内垂直居中,配合内部文本居中实现整体居中
GridPane.setValignment(firstLbl, VPos.CENTER);
grid.add(ins2View, 1, 0, 1, 1);
grid.add(ins3View, 2, 0, 1, 1);

grid.setHgap(20);
grid.setVgap(20);
grid.setPadding(new Insets(40, 40, 40, 40));

额外说明

  • 移除prefHeight后,Label会根据文本行数自动计算所需高度,setMaxHeight(Double.MAX_VALUE)避免高度被系统限制
  • RowConstraints的Vgrow(Priority.ALWAYS)设置,让GridPane的目标行可以随Label高度自动扩展,不会出现单元格高度不足的情况
  • GridPane.setValignment确保Label在单元格内垂直方向居中,搭配Label自身的Pos.CENTER,实现文本在单元格内的完全居中效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:15:27