3

I want to show text of unknown length in a window. The text should be wrapped if it reaches the border of the window. The initial height of the window should match the height of the text. And if the user resizes the window, the width of the text should also be changed.

How can I achieve this in JavaFX without eventHandlers?

If I use a Label, the text is wrapped and also changes its width, but the initial height of the window does not fit the entire text, so the text is clipped.

using Label

If I use Text (Text-tag), I need to specify a wrapping width. The window ́s height is correct, but if I resize the window, the width of the text does not change.

using Text

asked Mar 28, 2015 at 9:17

1 Answer 1

2

In case, you want to use a Text you can bind its wrappingWidthProperty to the scenes's widthProperty.

public class Main extends Application {
 @Override
 public void start(Stage primaryStage) throws Exception{
 VBox layout = new VBox(25);
 Text text = new Text("bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla blabla bla bla bla bla bla bla bla bla bla bla blabla bla bla blabla bla bla blabla bla bla bla");
 layout.getChildren().add(text);
 Scene scene = new Scene(layout, 200, 200);
 primaryStage.setScene(scene);
 text.wrappingWidthProperty().bind(scene.widthProperty().subtract(15));
 primaryStage.show();
 }
 public static void main(String[] args) {
 launch(args);
 }
}

Similarly, in case you want to use a Label, you can bind its prefHeightProperty with the scene's heightProperty.

label.setWrapText(true);
label.prefHeightProperty().bind(scene.heightProperty());
answered Mar 28, 2015 at 10:30
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.