我有一个窗口/舞台和一个TextArea,它将根据TextArea中文本的长度进行调整(文本被包装)。这意味着,窗口越小,TextArea中的文本越少。给出了TextArea的宽度。要计算TextArea的高度,我使用文本的长度,TextArea的给定宽度和行高。例如:
double height = textwidth / agreement.getWidth()* 18;
在这种情况下,行高由静态值定义。但是行高必须根据css文件中的定义而变化,因为如果字体大小的定义发生变化,行高会发生变化。因此,我需要确定TextArea的行高,以使用它而不是使用静态值。那么,我怎样才能获得TextArea的行高?
答案 0 :(得分:2)
一旦显示舞台,您就可以找到文本区域中呈现的文本的确切尺寸:
@Override
public void start(Stage primaryStage) {
TextArea area = new TextArea("This is some random very long text");
area.setWrapText(true);
area.setPrefWidth(200);
area.setMaxWidth(200);
area.setStyle("-fx-font: 18pt Arial");
StackPane root = new StackPane(area);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
Text t = (Text)area.lookup(".text");
System.out.println("LayoutX "+t.getLayoutX());
System.out.println("LayoutY "+t.getLayoutY());
System.out.println("Width: "+t.getBoundsInLocal().getWidth());
System.out.println("Height: "+t.getBoundsInLocal().getHeight());
}
根据这些尺寸,您可以执行计算。
修改强>
您可以在显示舞台之前获取尺寸,但为此您需要将CSS样式应用于根和子项并强制在场景上布局:
Scene scene = new Scene(root, 300, 250);
root.applyCss();
root.layout();
Text t = (Text)root.lookup(".text");
System.out.println("LayoutX "+t.getLayoutX());
System.out.println("LayoutY "+t.getLayoutY());
System.out.println("Width: "+t.getBoundsInLocal().getWidth());
System.out.println("Height: "+t.getBoundsInLocal().getHeight());
// Now calculations can be performed
primaryStage.setScene(scene);
primaryStage.show();