JavaFX resize text with window

ε祈祈猫儿з 提交于 2019-12-24 10:45:53

问题


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


来源:https://stackoverflow.com/questions/29315469/javafx-resize-text-with-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!