Thomas Escolan
Thomas Escolan

Reputation: 1529

libgdx - place a table on the top-right corner of the screen

I'm experiencing an issue placing a "table" in the top-right corner of my screen:

|----------|
|         X|
|          |
|          |
|----------|

Table statusTable = new Table(skin);
statusTable.add(new DateLabel(skin));
statusTable.row();
statusTable.add(new TextButton("Funds:", skin));
statusTable.row();
statusTable.add(new TextButton("Tax rate:", skin));
...
this.statusTable.setPosition(width, height, Align.bottomLeft);

Reaching the #setPosition point, the table's width and height are set to 0 so the positioning stands centered on the corner somehow:

|----------X
|          |
|          |
|          |
|----------|

I guess I don't understand well what this alignment is about, and before coding my own algorithm I'd like to know if a better practice would exist.

Thanks for any comment.

Upvotes: 0

Views: 1063

Answers (2)

Tenfour04
Tenfour04

Reputation: 93779

If you are adding the table directly to the stage (e.g. it is not inside some other table), it would be easier to set the table widget to fill it's parent, and then set its gravity to the top right so its logical table (the actual cells within the widget) is pulled up to the corner.

Table statusTable = new Table(skin);
statusTable.add(new DateLabel(skin));
statusTable.row();
statusTable.add(new TextButton("Funds:", skin));
statusTable.row();
statusTable.add(new TextButton("Tax rate:", skin));

// ...

statusTable.top().right();
statusTable.setFillParent(true);
stage.addActor(statusTable);

By the way, the reason your method didn't work is that the table's size hasn't been calculated yet if it hasn't been drawn yet, and you're using the opposite corner of what you want to align. You could call statusTable().pack() before your setPosition call, and it should work assuming width and height are the coordinates of the top right corner of the viewport and you used Align.topRight.

Upvotes: 4

Lordeblader
Lordeblader

Reputation: 96

Size is computed at runtime, and since you don't know the size of the table, I would let another table calculate its position.

I would add an empty expanded cell before the statusTable, both inside a rootTable that fills the entire stage (using setFillParent())

┌────────┬───┐
│        │ X │ -> empty expandX cell | statusTable | row
├────────┴───┤
│            │
│            │ -> empty expand, colspan(2) cell
│            │
└────────────┘

Another 'solution' could be setting the table position at runtime

Table statusTable = new Table(skin) {
    @Override
    public void act(float delta) {
        super.act(delta);
        setPosition(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), Align.topRight);
    }

};

Upvotes: 1

Related Questions