JavaFX使用窗口调整文本大小 [英] JavaFX resize text with window

查看:456
本文介绍了JavaFX使用窗口调整文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在窗口中显示未知长度的文本。如果文本到达窗口边界,则应将其包装。窗口的初始高度应与文本的高度相匹配。如果用户调整窗口大小,则还应更改文本的宽度。

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.

如何在没有eventHandlers的情况下在JavaFX中实现此目的?

How can I achieve this in JavaFX without eventHandlers?

如果我使用Label,文本将被包装并更改其宽度,但窗口的初始高度不适合整个文本,因此文本被剪裁。

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.

如果我使用Text(文本标签),我需要指定包装宽度。窗口的高度是正确的,但如果我调整窗口大小,文本的宽度不会改变。

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.

推荐答案

如果您想使用 Text 您可以将 wrappingWidthProperty 绑定到场景的widthProperty

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

同样,如果你想使用标签,您可以使用场景的heightProperty 绑定其<$​​ c $ c> prefHeightProperty 。

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

这篇关于JavaFX使用窗口调整文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆