5

I want to swap the positions of two labels inside a table of libGDX. I thought I may use swapActors to do this, but it doesn't do the trick.

private Stage stage;
private Table table;

public MainScreen() {

    stage = new Stage(new FitViewport(800, 480));
    table = new Table(SkinManagerImpl.getDefaultSkin());
    table.add("A").center();
    table.add("B").center();
    table.setFillParent(true);
    boolean succes=table.swapActor(0, 1);
    Gdx.app.log("", "success:"+succes);
    table.layout();
    stage.addActor(table);
}

@Override
    public void render(float delta) {
        // TODO Auto-generated method stub
        super.render(delta);
        stage.draw();
    }

success is true, but it still says "AB" and not "BA" as wanted.

Is there another simple way to swap two cells or actors (meaning swap positions) inside a table?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
angelnoir
  • 51
  • 3

2 Answers2

3

Have a look at the " public Cell getCell(T actor) " method in the API docs.

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Table.html#getCell-T-

Now have a look at the Cell docs:

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Cell.html

You can get the Actor instance that is in each Cell instance, and then swap them using a regular old swap method. Use Cell.getActor and Cell.setActor. Easy peasy.

Scuba Steve
  • 1,541
  • 1
  • 19
  • 47
0

I've had the exact same problem and approach as you did and after tinkering around for a while I found out that table.swapActor works perfectly fine, if you DO NOT call layout.

This makes sense once you look up the source code. It seems as if as though layout() reassigns the previously removed actors to their original position.

Oh, and adding a scene2d action makes this look really nice :)