JavaFX resize text with window

2019-08-04 01:46发布

问题:

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.

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.

回答1:

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