按钮只是libgdx中的一个actor。要渲染一个演员,您可以使用一个包含屏幕上所有演员的舞台,渲染它们并对其进行更新。我假设您想要一个带有文本的按钮,因此您应该使用TextButton类并将其添加到舞台上。一个TextButton接受一个字符串进行渲染,并使用一个ButtonStyle,在这种情况下为TextButtonStyle,它基本上是一个类,其中包含有关按钮的所有信息(字体,不按下时可绘制,按下时可绘制等)。
public class ButtonExample extends Game{ Stage stage; TextButton button; TextButtonStyle textButtonStyle; BitmapFont font; Skin skin; TextureAtlas buttonAtlas; @Override public void create() { stage = new Stage(); Gdx.input.setInputProcessor(stage); font = new BitmapFont(); skin = new Skin(); buttonAtlas = new TextureAtlas(Gdx.files.internal("buttons/buttons.pack")); skin.addRegions(buttonAtlas); textButtonStyle = new TextButtonStyle(); textButtonStyle.font = font; textButtonStyle.up = skin.getDrawable("up-button"); textButtonStyle.down = skin.getDrawable("down-button"); textButtonStyle.checked = skin.getDrawable("checked-button"); button = new TextButton("Button1", textButtonStyle); stage.addActor(button); } @Override public void render() { super.render(); stage.draw(); }}那么这里发生了什么?我在“
buttons.pack”中创建一个带有所有按钮纹理的舞台,一个字体和一个textureatlas。然后,我初始化一个空的TextButtonStyle,并为上,下和选中状态添加字体和纹理。font,up,down和checked都是Drawable类型的静态变量,因此您可以真正将其传递给任何类型的Drawable(纹理,9-patch等)。然后只需将按钮添加到舞台即可。
现在,为了在实际单击按钮时执行某些操作,您必须向按钮添加一个侦听器,即ChangeListener。
button.addListener(new ChangeListener() { @Override public void changed (ChangeEvent event, Actor actor) { System.out.println("Button Pressed"); } });当然,除了将按钮直接添加到舞台上之外,您应该将其添加到表格中并将表格添加到舞台上,但是我不想让这篇文章过于混乱。这是关于libgdx中表的很好的教程。



