Bine
Bine

Reputation: 394

JavaFX: Get line height of TextArea

I have a window/stage and a TextArea which will be resized dependent on the length of the text inside the TextArea (the text is wrapped). This means, the window is smaller, the less the text is inside the TextArea. The width of the TextArea is given. To calculate the height of the TextArea I use the length of the text, the given width of the TextArea and the line height. For example:

double height=textwidth/agreement.getWidth()*18;

In this case the line-height is defined by a static value. But the line height have to be variable dependent on the definitions in the css-file, because the line height changes if the definition of the font size changes. Consequently I need to determine the line height of the TextArea to use it instead of using a static value. So, how can I get the line height of a TextArea?

Upvotes: 0

Views: 2668

Answers (1)

José Pereda
José Pereda

Reputation: 45456

You can find the exact dimensions of the text rendered in the text area, once the stage is shown:

@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());
}

Based on those dimensions, you can perform your calculations.

EDIT

You can get the dimensions before showing the stage, but for that you need to apply CSS styling to the root and children and force a layout on the scene:

    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();

Upvotes: 2

Related Questions