Search code examples
javabuttonlibgdximagebutton

LibGDX how to get button from clickListener


To be honest I have no idea what I'm doing wrong. I want to get ImageButton object from ClickListener, but something goes wrong.

 public void createButton() {
    button = new ImageButton(this.skin);
    buttonUnitsList.add(button);
    button.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
           selectedUnit = buttonUnitsList.indexOf(this.getButton());
        }
    });       
}

Solution

  • To get Actor instance on which event was fired you need to use getTarget() Event's method. If you are sure that the listener will be used only with buttons you can upcast this from Actor to Button

    selectedUnit = buttonUnitsList.indexOf((Button)event.getTarget());
    

    Notice that if you will use the listener for another type of Actor you will get casting Exception