JCodes13 JCodes13 - 7 months ago 12
Java Question

libgdx clickable image not working

I have a menu screen in libgdx and I had a text button that started a new game like this.

textButton.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
g.setScreen( new level1(g));
}
});


It looked like crap so I changed it to an image.

playbuttontexture = new Texture(Gdx.files.internal("data/playbutton.png"));
playbuttontexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

TextureRegion playbuttonregion = new TextureRegion(playbuttontexture, 0, 0, 512, 256);//powers of 2

playbutton = new Image(playbuttonregion);
playbutton.setSize(512,256);
playbutton.setBounds(width/2-playbutton.getWidth()/2, height/2-playbutton.getHeight()/2, 512, 256);
//playbutton.setOrigin(playbutton.getWidth()/2, playbutton.getHeight()/2);
playbutton.setPosition(width/2-playbutton.getWidth()/2, height/2-playbutton.getHeight()/2);


and

playbutton.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
g.setScreen( new level1(g));
}
});


Now when I click it nothing happens? What am I doing wrong?

Answer

The problem here is that Image does not fire a changed(...) event anymore. This event is only fired by the TextButton you've used before when the status changes from clicked to not-clicked and the other way around. It can also be fired in other cases, since it is kind of a "generic" event, as the JavaDoc states, but that varies from actor to actor.

Change it to a ClickListener and use the clicked(...) method instead. This event should be fired by all actors in the scene2d.ui package.

Comments