Get user input with textbox class

Looking at your sample code that uses GTextField there are a number of things worth mentioning but first of all the error is caused because you attempted to use setText("test2"); while the textfield still had focus (the text insertion cursor is flashing). If you enter some text in the textfield and then click outside the textfield before pressing ENTER then it works.

NEVER use setText(...) while the textfield has focus, same thing applies to GPassword and GTextArea.

All G4P control use event handlers to process events. Here is an example of how to use a textfield

import g4p_controls.*;


GTextField txf1;
String t0;

public void setup() {
  size(500, 300);

  txf1 = new GTextField(this, 10, 10, 200, 20);
  txf1.setPromptText("Text field 1");
  txf1.setText("test1"); // works
}

public void draw() {
  background(200, 128, 200);

  if (keyPressed && key == ENTER) {
    println(t0);
  }
}

public void handleTextEvents(GEditableTextControl textcontrol, GEvent event) {
  if(txf1 == textcontrol && event == GEvent.ENTERED){
    t0 = txf1.getText();
  }
}

You will find more information about G4P on my website also look at the G4P Programmer Guides

4 Likes