Java 如何获得带有包装文本的标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18557448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a Label with wrapped text?
提问by talloaktrees
I ave tried the following code:
我尝试了以下代码:
Label label = new Label(reallyLongString, skin);
label.setWrap(true);
label.setWidth(100); // or even as low as 10
table.add(label);
...
and yet all I get is a very wide line that draws off the screen. How to get a Label with wrapped text?
然而我得到的只是一条很宽的线,从屏幕上划出来。如何获得带有包装文本的标签?
采纳答案by BennX
This is the same issue as seen in slider always has default widthor "Slider always has default width".
这与在slider always has default width或"Slider always has default width" 中看到的问题相同。
You need to put that label into a table and add the right size to the cell of the table where the label is.
您需要将该标签放入表格中,并将正确的大小添加到标签所在表格的单元格中。
UI widgets do not set their own size and position. Instead, the parent widget sets the size and position of each child. Widgets provide a minimum, preferred, and maximum size that the parent can use as hints. Some parent widgets, such as Table, can be given constraints on how to size and position the children. To give a widget a specific size in a layout, the widget's minimum, preferred, and maximum size are left alone and size constraints are set in the parent.
UI 小部件不会设置自己的大小和位置。相反,父小部件设置每个子部件的大小和位置。小部件提供了父母可以用作提示的最小、首选和最大尺寸。某些父小部件(例如 Table)可以在如何调整子部件的大小和位置方面受到限制。要在布局中为小部件提供特定大小,小部件的最小、首选和最大大小将保持不变,并在父级中设置大小限制。
Source: From the libgdx wiki Scene2D
The solution:
解决方案:
Label label = new Label(reallyLongString, skin);
label.setWrap(true);
label.setWidth(100); // or even as low as 10
table.add(label).width(10f);// <--- here you define the width
回答by Will Iverson
If you just want to specify the preferred size for a single widget, wrap it with a Container.
如果您只想为单个小部件指定首选大小,请使用 Container 包装它。
https://github.com/libgdx/libgdx/wiki/Scene2d.ui#layout-widgets
https://github.com/libgdx/libgdx/wiki/Scene2d.ui#layout-widgets
Something like:
就像是:
Container<Label> labelContainer = new Container(myLabel);
labelContainer.prefWidth(200.0f);
Keep in mind that the actual size will vary depending on the container hierarchy - for example, the labelContainer above will display differently if placed in another layout object.
请记住,实际大小将根据容器层次结构而有所不同 - 例如,如果放置在另一个布局对象中,上面的 labelContainer 将显示不同。
The size will also vary depending on the viewport, etc.
大小也会因视口等而异。
回答by Vokail
I've found that the following code can solve the issue without any table or wrapping container (for libgdx-1.9.6):
我发现以下代码可以在没有任何表或包装容器的情况下解决问题(对于 libgdx-1.9.6):
label = new Label("Some label", skin);
label.setPosition(600, 50);
label.setWidth(200);
label.setHeight(50);
label.setWrap(true);
stage.addActor(label);