Search code examples
javalibgdx

How do I add an image/texture to my table in libGDX?


I made a table for a simple HUD which displays health, score and the current weapon from the player. The weapon should be displayed as an image, but my program crashes if I try to do so. It works fine if I use a number, so there is no error in my code.

public class Hud {
    public Stage stage;
    private Viewport viewport;

    private int health;
    private int score;
    private Texture weaponImage;

    Label healthLabel;
    Label scoreLabel;
    Label weaponLabel;

    public Hud(SpriteBatch spriteBatch) {
        health = 100;
        score = 0;
        weaponImage = new Texture(Gdx.files.internal("sword.png"));

        viewport = new FitViewport(MyProject.V_HEIGHT, MyProject.V_HEIGHT, new OrthographicCamera());
        stage = new Stage (viewport, spriteBatch);

        Table table = new Table();
        table.top();
        table.setFillParent(true);

        healthLabel = new Label(String.format("%03d", health), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
        scoreLabel = new Label(String.format("%03d", score), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
        //Here should be the code to display the image

        table.add(healthLabel).expandX().padTop(10);
        table.add(scoreLabel).expandX().padTop(10);

        stage.addActor(table);
    }
}

Solution

  • Found out how to do it: Instead of a texture, I created an image.

    weaponImg = new Image(new Texture(Gdx.files.internal("sword.png")));
    

    It worked fine when I added the following code in the HUD method:

    table.add(weaponImg).width(50).height(100);