Search code examples
libgdxscene2d

LibGDX - How to increase a cell's size without affecting its content?


I'm experimenting with LibGDX's Scene2d and I wrote this simple code:

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;

public class UITest extends ApplicationAdapter {

    private Stage stage;

    public static void main(String[] args) {
        LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
        configuration.title = "UI Test";
        configuration.width = 800;
        configuration.height = 600;
        new LwjglApplication(new UITest(), configuration);
    }

    @Override
    public void create() {
        this.stage = new Stage();

        Skin skin = new Skin(Gdx.files.internal("skins/default.json"));

        Table table = new Table();
        table.setFillParent(true);
        table.add(new Label("Text", skin));

        table.debugAll();

        this.stage.addActor(table);
    }

    @Override
    public void render() {
        this.stage.draw();
    }
}

Which produces the following when run:

teste

Now I wanted to align the cell's content to the top left. To do this, I set the cell's width and height to 100 and apply the alignments, like so:

table.add(new Label("Text", skin)).width(100).height(100).top().left();

Which causes the cell's content to increase alongside the cell:

enter image description here

Is this the expected behaviour? If so, is there a way to increase the cell's size without affecting its content?

Using the cell's expand method does not affect its content, however I wanted to have a more precise control over the cell's size, setting it to a specific value or percentage.


Solution

  • That's expected. When you set an explicit size on a cell, the same size is applied to the actor in the cell.

    To get the behavior you want, you should set the table itself to the overall size you want. Then use expand() on the cell to make it fill the table. Since you haven't set an explicit size on the cell, the actor still has control over its own size and you use alignment on its cell to align it in the cell.

    Or alternatively you could simply set alignment on the Label directly and it will align the text within itself even though the Label Actor is filling the cell.