Cannot show user input with a textfield

2019-07-23 15:09发布

问题:

I'm trying to use a TextField to get some user input:

 public void render() {
    Gdx.gl.glClear(GL11.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(0, 0, 0, 0);

    batch.begin();
    batch.end();
    stage = new Stage();
    Gdx.input.setInputProcessor(stage);
    Skin skin = new Skin(Gdx.files.internal("assets/uiskin.json"));

    TextButton btnLogin = new TextButton("Click", skin);
    btnLogin.setPosition(300, 300);
    btnLogin.setSize(300, 60);
    btnLogin.addListener(new ClickListener() {
        public boolean touchDown(InputEvent e, float x, float y, int point, int button) {
            System.out.println(txfUsername.getText());
            return false;
        }
    });

    txfUsername = new TextField("", skin);
    txfUsername.setPosition(300, 250);
    txfUsername.setSize(300, 40);

    stage.addActor(txfUsername);           
    stage.addActor(btnLogin);

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

All I get is a blank field. The user can't interact with it in any way.

I followed the instructions in this video How do I make the textfield editable?

回答1:

You use txfUsername = new TextField ("", skin); in your render method. That creates a new TextField from scratch on each render.

public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);


    batch.begin();
    // do other rendering ...
    batch.end();

    Gdx.app.log("MyTextField", txfUsername.getText());

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

In your class variables:

private TextButton btnLogin;
TextField txfUsername;

In your method show or create (not render):

@Override
public void show() {

    btnLogin = new TextButton("Click", skin);

    btnLogin.setPosition(300, 300);
    btnLogin.setSize(300, 60);
    btnLogin.addListener(new ClickListener() {
        public boolean touchDown(InputEvent e, float x, float y, int point, int button) {
            System.out.println(txfUsername.getText());
            return false;
        }
    });

    txfUsername = new TextField("", skin);
    txfUsername.setPosition(300, 250);
    txfUsername.setSize(300, 40);

    stage.addActor(txfUsername);           
    stage.addActor(btnLogin);
}

Use txfUsername.getText(); written for the field

Edit: I do not know how you worked with GL11, if GL10, I could understand a you malfunction, if you get error in GL10, you should update libgdx, GL10 is an interface and I think last versions for in libgdx not bring already