如何在Libgdx中创建一个按钮?

jul*_*ian 29 java libgdx scene2d

我想创建一个按钮,当用户将其悬停或单击时,该按钮会发生变化.我创建了以下变量

Button buttonPlay = new Button();
Run Code Online (Sandbox Code Playgroud)

我现在不知道该怎么办,如何加载图片?如何在按钮中写入文字?如何实现事件/效果(悬停,点击)?

如果有人可以为按钮编写一些示例代码,那将非常有用.

dan*_*elz 71

按钮只是libgdx中的一个actor.要渲染一个actor,你使用一个包含屏幕所有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();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么这里发生了什么?我正在创建一个舞台,一个字体和一个带有"buttons.pack"按钮所有纹理的纹理图.然后我初始化一个空的TextButtonStyle,并为上,下和检查状态添加字体和纹理.font,up,down和checked都是Drawable类型的静态变量,所以你可以真正传递任何类型的Drawable(纹理,9补丁等).然后只需将按钮添加到舞台即可.

现在,为了在实际单击按钮时执行某些操作,您必须向按钮添加一个侦听器,即ChangeListener.

    button.addListener(new ChangeListener() {
        @Override
        public void changed (ChangeEvent event, Actor actor) {
            System.out.println("Button Pressed");
        }
    });
Run Code Online (Sandbox Code Playgroud)

当然不是直接将按钮添加到舞台上,而是应该将它添加到表格中并将表格添加到舞台中,但我不想让这个帖子太混乱.是一个关于libgdx中表的好教程.

  • 非常感谢你!!它是如此有用,只有一个问题..如何创建`buttons.pack`文件? (2认同)
  • 很好的教程:http://libdgxtutorials.blogspot.com/2013/09/libgdx-tutorial-10-button-and-stage-2d.html (2认同)

Hit*_*ahu 5

这就是在不添加任何皮肤的情况下做到这一点的方法

    TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
    textButtonStyle.font = yourCustomFont;
    textButtonStyle.fontColor = Color.WHITE;
    stage.add(new TextButton("Custom Btn ", textButtonStyle));
Run Code Online (Sandbox Code Playgroud)