Search code examples
javalibgdx

How to use timer with libgdx?


I'm trying to use the gdx Timer to increment a value repeatedly but when I use this value inside a Label it seems like nothing happens and the value is stuck at 0 , here is my code for the timer :

@Override
    public void show() {
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        Skin skin = new Skin(Gdx.files.internal("gui/uiskin.json"));
        table = new Table(skin);
        table.setFillParent(true);

        atlas = new TextureAtlas("gui/atlas.pack");
        skin2 = new Skin(Gdx.files.internal("gui/MenuSkin.json"), atlas);


        DragAndDrop dragAndDrop = new DragAndDrop();



        // My tables 
        inventoryActor = new InventoryActor(new Inventory(16, 3), dragAndDrop, skin, "Game Pad");
        inventoryActor2 = new InventoryActor(new Inventory(25), dragAndDrop, skin, "Inventory Pad");

        // bc image

        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("et2.jpg"));

        Timer.schedule(new Task(){
            @Override
            public void run() {
                timing++;
            }
        }, 1);

        heading = new Label("Good Luck"+(timing++), skin2, "big");

        //Timer task


        //timerCount = new Label("Time : "+timing+" s",skin2, "small");


        back = new TextButton("Back", skin2, "small");
        back.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                ((Game) Gdx.app.getApplicationListener()).setScreen(new GameOption());
            }
        });
        back.pad(10);

        table.add(heading).colspan(3).expandX().spaceBottom(50).row();
        table.add(inventoryActor2).uniformX().expandY().top().left().padLeft(30);
        table.add(inventoryActor).top().spaceLeft(30);
        table.add(back).bottom().right();
        stage.addActor(table);



    }


@Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        /*if (Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)) {

        }*/

            batch.begin();
            batch.draw(texture, 10, 10);
            batch.end();

        inventoryActor.setVisible(true);
        inventoryActor2.setVisible(true);

        stage.act(delta);
        stage.draw();

    }

Solution

  • The problem is, that you never set your Labels text inside the show() method. You only give it an initial text as a String in the constructor, so the Label doesn't know, that the timing has changed. So you should set the Labels text in the render() before calling stage.draw().