Question

I have created a screen in my application that shows a text field and a button but for some reason I cannot click on them. Do you have any idea what might be the reason. That's my code (I skipped the variable declarations):

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);
}
   }
Was it helpful?

Solution

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);

All this should not be in your render() method. Instead, put the instantiation in the show() method or in your consctructor. It will also dramatically reduce the lag.

Why are your buttons not working: You instantiate a new Stage each frame, and assign the InputProcessor to it. There is no moment in your actual code to process the actual input.

Here is what your class should look like:

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);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top