Search code examples
javaandroidlibgdx

Multilne text. Libgdx


How to crate a multiline text? I tried to use Label , but text have only 1 line.

Table table = new Table();
table.setPosition(0,0);
table.setSize(800,440);

label = new Label("Some long string here...", skin);
label.setFillParent(true);
label.setAlignment(center);
label.setPosition(0,0);
label.setWidth(40);
label.setHeight(label.getPrefHeight());
label.setText(tutortext);

table.addActor(label);

stage.addActor(table);
stage.setDebugAll(true);

https://i.sstatic.net/3whQr.png


Solution

  • Use setWrap(true); on label.

    According to doc.

    • If false, the text will only wrap where it contains newlines (\n). The preferred size of the label will be the text bounds.
    • If true, the text will word wrap using the width of the label. The preferred width of the label will be 0, it is expected that something external will set the width of the label. Wrapping will not occur when ellipsis is enabled. Default is false.

    • When wrap is enabled, the label's preferred height depends on the width of the label. In some cases the parent of the label will need to layout twice: once to set the width of the label and a second time to adjust to the label's new preferred height.

    I've tested with small example :

    public class MultiLine extends ApplicationAdapter {
    
        Stage stage;
        Skin skin;
    
        @Override
        public void create() {
    
            stage=new Stage();
    
            skin=new Skin(Gdx.files.internal("skin/glassy-ui.json"));
    
            Label label=new Label("MULTILINE IN LIBGDX GAME DEVELOPMENT",skin);
            label.setWrap(true);
    
            Table table=new Table();
            table.setFillParent(true);
    
            table.add(label).width(150);
    
            stage.addActor(table);
        }
    
        @Override
        public void render() {
    
            Gdx.gl.glClearColor(0,0,0,0);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
            stage.draw();
            stage.act();
        }
    
        @Override
        public void dispose() {
            stage.dispose();
            skin.dispose();
        }
    }
    

    Here is the output :

    enter image description here