且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaFX 2:自动换行在ScrollPane中不起作用

更新时间:2023-09-25 19:48:16

引用Javadoc:

public final void setWrapText(boolean value)

属性描述:

如果一行文本超出了Labeled的宽度,则此变量指示是否应将文本换行到另一行.

在您的示例中,因为您没有为标签设置大小,它会自动调整大小以适合所有文本.因此Label知道您要他包装文字,但是当文字适合他的宽度时,他什么也没做.

Well in your example as you did not set a size to your label it automatically sized to fit all the text. So the Label understood you wanted him to wrap the text but as the text fitted his width then he didn't do a thing.

现在,如果您为标签设置一个首选尺寸,它将迫使他包装文字:

Now, if you set a pref size for your label like that it will force him to wrap the text:

    label.setPrefSize(250, 500);

您可以做的(这可能是一个更好的方法)是告诉您ScrollPane使用setFitToWidthsetFitToHeight方法调整其内部组件的大小.就是这样:

What you can do (and it's probably a better way) is tell your ScrollPane to resize components inside it using the setFitToWidth or setFitToHeight methods. Just like this :

    scroll.setFitToWidth(true); 

调整窗口大小时,Label的大小将调整为适合ScrollPane的大小,并且文本将相应地换行.

When you resize your window, the Label will be resized to fit the size the ScrollPane, and your text will be wrapped accordingly.

另一种实现所需功能的方法是使用文本对象而不是标签:

Another way to achieve what you want is using a Text Object instead of a Label :

Text text = new Text("Lorem ipsum dolor sit amet, consectetur adipisicing elit," +
            " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim" +
            " ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip" +
            " ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate" +
            " velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat" +
            " cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum");

    text.setWrappingWidth(250);