How to get a Label with wrapped text?

I've found that the following code can solve the issue without any table or wrapping container (for 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);

If you just want to specify the preferred size for a single widget, wrap it with a Container.

https://github.com/libgdx/libgdx/wiki/Scene2d.ui#layout-widgets

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Container.html

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.

The size will also vary depending on the viewport, etc.


This is the same issue as seen in slider always has default width or "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.

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

Tags:

Java

Label

Libgdx