JavaFx:调整大小,当窗格包含文本时

JavaFx:调整大小,当窗格包含文本时,java,javafx,Java,Javafx,在JavaFX中,我在AnchorPane(或StackPane)内部、容器窗格内部有一个标签(或TextFlow) 容器窗格具有无限高,但其宽度固定为我想要的任何值 我需要: Pane rootPane = new Pane(); rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY))); AnchorPane anchorPane =

在JavaFX中,我在AnchorPane(或StackPane)内部、容器窗格内部有一个标签(或TextFlow)

容器窗格具有无限高,但其宽度固定为我想要的任何值

我需要:

Pane rootPane = new Pane();
rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane anchorPane = new AnchorPane();
anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
Label text = new Label("text text text text text text text text text text text");
anchorPane.getChildren().add(text);
rootPane.getChildren().add(anchorPane);
1) 锚烷的宽度,以填充所有可用空间,但不大于标签的宽度时,它适合所有在一行

2) 标签应为多行(wrap=true),并填充所有可用空间

3) 锚烷的高度应等于标签的高度

代码设置:

Pane rootPane = new Pane();
rootPane.setBackground(new Background(new BackgroundFill(Color.FIREBRICK, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane anchorPane = new AnchorPane();
anchorPane.setBackground(new Background(new BackgroundFill(Color.FORESTGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
Label text = new Label("text text text text text text text text text text text");
anchorPane.getChildren().add(text);
rootPane.getChildren().add(anchorPane);

或者,我可以使用以下标签代替标签:

TextFlow text = new TextFlow(new Text("text text text text text text text text text text text"));
我在这个问题上浪费了好几个小时。这在HTML中非常简单。。。如何实现这一点?

代码
导入javafx.application.application;
导入javafx.beans.value.ChangeListener;
导入javafx.beans.value.observeValue;
导入javafx.geometry.Insets;
导入javafx.scene.scene;
导入javafx.scene.control.Label;
导入javafx.scene.layout.ancorpane;
导入javafx.scene.layout.Background;
导入javafx.scene.layout.BackgroundFill;
导入javafx.scene.layout.CornerRadii;
导入javafx.scene.layout.Pane;
导入javafx.scene.paint.Color;
导入javafx.stage.stage;
公共类主扩展应用程序{
@凌驾
public void start(Stage primaryStage)引发异常{
窗格根窗格=新窗格();
标签文本=新标签();
text.setWrapText(true);
text.setText(“文本”);
锚烷锚烷=新锚烷();
anchorPane.getChildren().add(文本);
主播。背景(新背景(新背景填充(颜色为森林绿,角半径为空,插图为空));
rootPane.getChildren().add(anchorPane);
根窗格.立根背景(新背景(新背景填充(Color.FIREBRICK,CornerRadii.EMPTY,Insets.EMPTY));
初始阶段。设置场景(新场景(根窗格,300275));
primaryStage.show();
rootPane.widthProperty().addListener(新的ChangeListener()){
私人双文本宽度;
@凌驾

更改公众假期(ObservaleValuePost一个简化版的
FXML
@SedrickJefferson我没有FXML。这不使用标签,但好的,我可以使用文本。但是问题是它会闪烁。要查看它,请尝试更长的文本。每隔调整一次就会出错。这是真的。在我的linux机器上没有看到它,因为我的窗口管理器没有调整大小时更新。标签/文本如何处理包装似乎存在一些问题。今天我将再次查看并更新我的答案。如何从屏幕捕获中制作这些动画GIF?您需要声明textWidth字段,对吗?:
private double textWidth;
我已添加声明。谢谢。