libgdx-scene2d无法单击小部件

mbzjlibv  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(241)

我在我的应用程序中创建了一个屏幕,显示一个文本字段和一个按钮,但由于某些原因,我无法单击它们。你知道原因是什么吗。这是我的代码(我跳过了变量声明):

public class SentenceScreen implements Screen {
public SentenceScreen(Game g) {
    game = g;
}

@Override
public void render(float delta) {
    // TODO Auto-generated method stub
    Gdx.gl.glClearColor(0,0,0,0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    stage = new Stage();

    Skin skin = new Skin(Gdx.files.internal("uiskin.json"));

    btnLogin = new TextButton("Click me", skin);
    btnLogin.setPosition(300, 50);
    btnLogin.setSize(100, 60);
    stage.addActor(btnLogin);

    textField = new TextField("", skin);
    textField.setPosition(100, 50);
    textField.setSize(190, 60);
    stage.addActor(textField);

    stage.act(delta);
    stage.draw();

    Gdx.input.setInputProcessor(stage);
}
   }
dgjrabp2

dgjrabp21#

stage = new Stage();

Skin skin = new Skin(Gdx.files.internal("uiskin.json"));

btnLogin = new TextButton("Click me", skin);
btnLogin.setPosition(300, 50);
btnLogin.setSize(100, 60);
stage.addActor(btnLogin);

textField = new TextField("", skin);
textField.setPosition(100, 50);
textField.setSize(190, 60);
stage.addActor(textField);

Gdx.input.setInputProcessor(stage);

所有这些都不应该出现在render()方法中。相反,将示例化放在show()方法或构造函数中。这也将大大减少滞后。
为什么您的按钮不起作用:您在每一帧中示例化一个新的stage,并将inputprocessor分配给它。在实际代码中没有时间处理实际输入。
以下是你的课堂应该是什么样子:

public class SentenceScreen implements Screen {
public SentenceScreen(Game g) {
    game = g;
}

@Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(0,0,0,0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

stage.act(delta);
stage.draw();
}

@Override
public void show() {

stage = new Stage();

Skin skin = new Skin(Gdx.files.internal("uiskin.json"));

btnLogin = new TextButton("Click me", skin);
btnLogin.setPosition(300, 50);
btnLogin.setSize(100, 60);
stage.addActor(btnLogin);

textField = new TextField("", skin);
textField.setPosition(100, 50);
textField.setSize(190, 60);
stage.addActor(textField);

Gdx.input.setInputProcessor(stage);
}
}

相关问题