Skip to content Skip to sidebar Skip to footer

Need Help In Using Scene2d Button In Libgdx

I am new to libGDX. I am trying to create a custom button by extending com.badlogic.gdx.scenes.scene2d.ui.Button. I want all the button related logic in this class. But I am not ge

Solution 1:

restartButton = new RestartButton(new ButtonStyle());
button.addListener(new ClickListener() {
    @Override
    publicvoidclicked(InputEvent event, float x, float y) {
        System.out.println("Restart clicked!");
    }
});
stage.addActor(restartButton);

Solution 2:

It does not work because you need to setBounds for your Button. If you wanted to draw the button in the position (175, 100) you could just create a Button directly from Button Class and call

button.setBounds(x, y, width, height);

Then adding the listener will work because now your button will actually have a position and an area in the stage. If you still need to extend the button class for your own reasons, you can set the bounds in the extended class ditectly or you can pass another argument in your RestartButton class. Similar to:

   public RestartButton(ButtonStyle style, Vector2 position, Vector2 size) {
       super(style);
       this.setBounds(position.x, position.y, size.x, size.y);
   }

Then the button will automatically be drawn to the position you want without the need of overriding draw method. add the listener by using this.addListener(yourListener);

Hope it helps.

Post a Comment for "Need Help In Using Scene2d Button In Libgdx"