如何让JavaFX文本自适应可用空间实现自动换行?
问题描述
我当前使用的FXML代码如下:
<HBox fx:id="mainTagBody" id="mainTagBodyInOverview" alignment="CENTER" xmlns="http://javafx.com/javafx" stylesheets="@/client/stylesheets/Global.css" xmlns:fx="http://javafx.com/fxml" fx:controller="client.scenes.TagInOverviewCtrl"> <HBox fx:id="tagContain" HBox.hgrow="ALWAYS"> <Text fx:id="tagText" text="test" wrappingWidth="${tagContain.prefWidth}" /> </HBox> <Button text="edit"/> <Button text="delete"/> </HBox>
目前显示存在两个问题:文本要么超出容器边界,要么拉伸整个容器导致布局偏移。尝试过多种方式设置wrappingWidth均未生效。
需求:让tagContain这个HBox占用所有可用空间时,文本自动换行,且完全不使用固定数值。
解决方案
方案一:用Label替代Text(推荐)
Label自带自动换行能力,无需手动绑定宽度,只需开启换行并让它占满容器空间:
<HBox fx:id="mainTagBody" id="mainTagBodyInOverview" alignment="CENTER" xmlns="http://javafx.com/javafx" stylesheets="@/client/stylesheets/Global.css" xmlns:fx="http://javafx.com/fxml" fx:controller="client.scenes.TagInOverviewCtrl"> <HBox fx:id="tagContain" HBox.hgrow="ALWAYS"> <Label fx:id="tagText" text="test" wrapText="true" HBox.hgrow="ALWAYS" /> </HBox> <Button text="edit"/> <Button text="delete"/> </HBox>
wrapText="true":开启Label的自动换行,会根据自身可用宽度自动折行HBox.hgrow="ALWAYS":让Label占满tagContain的全部宽度,而tagContain已通过HBox.hgrow="ALWAYS"占用mainTagBody的剩余空间,实现完全适配。
方案二:坚持使用Text控件
需要绑定Text的wrappingWidth到tagContain的实时实际宽度(而非首选宽度),并在控制器中完成绑定:
FXML代码:
<HBox fx:id="mainTagBody" id="mainTagBodyInOverview" alignment="CENTER" xmlns="http://javafx.com/javafx" stylesheets="@/client/stylesheets/Global.css" xmlns:fx="http://javafx.com/fxml" fx:controller="client.scenes.TagInOverviewCtrl"> <HBox fx:id="tagContain" HBox.hgrow="ALWAYS" fillHeight="true"> <Text fx:id="tagText" text="test" /> </HBox> <Button text="edit"/> <Button text="delete"/> </HBox>
控制器代码:
public class TagInOverviewCtrl implements Initializable { @FXML private HBox tagContain; @FXML private Text tagText; @Override public void initialize(URL url, ResourceBundle resourceBundle) { // 绑定Text的换行宽度到容器的实时实际宽度 tagText.wrappingWidthProperty().bind(tagContain.widthProperty()); } }
widthProperty()获取的是容器渲染后的实际宽度,而非prefWidth代表的首选宽度,这样Text能实时跟随容器宽度变化自动换行。
内容的提问来源于stack exchange,提问作者hellwraiz
相关产品推荐
相关产品推荐

