问题; textArea 的高度希望在其文本通过用户键入或复制粘贴而改变时增加或缩小。这是另一种方法:
public class TextAreaDemo extends Application {
private Text textHolder = new Text();
private double oldHeight = 0;
@Override
public void start(Stage primaryStage) {
final TextArea textArea = new TextArea();
textArea.setPrefSize(200, 40);
textArea.setWrapText(true);
textHolder.textProperty().bind(textArea.textProperty());
textHolder.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
if (oldHeight != newValue.getHeight()) {
System.out.println("newValue = " + newValue.getHeight());
oldHeight = newValue.getHeight();
textArea.setPrefHeight(textHolder.getLayoutBounds().getHeight() + 20); // +20 is for paddings
}
}
});
Group root = new Group(textArea);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
// See the explanation below of the following line.
// textHolder.setWrappingWidth(textArea.getWidth() - 10); // -10 for left-right padding. Exact value can be obtained from caspian.css
}
public static void main(String[] args) {
launch(args);
}
}
但它有一个缺点;仅当多行之间存在换行符(即 Enter 键)时,textarea 的高度才会发生变化,如果用户键入的时间足够长,则文本会被换成多行但高度不会改变。
为了解决这个缺点,我添加了这一行
textHolder.setWrappingWidth(textArea.getWidth() - 10);
之后primaryStage.show();
。它适用于用户不换行的长打字。然而,这产生了另一个问题。当用户通过点击“退格”删除文本时,会出现此问题。当 textHolder 的高度发生变化并且 textArea 的高度设置为新值时,就会出现问题。IMO 它可能是一个错误,没有更深入地观察。
在这两种情况下,复制粘贴都可以正确处理。