Getting text input is nice if the user has a field to type in to.
The sample code uses a keyPressed method that runs every time a key on the keyboard is pressed.
lastInput and currentInput are string "objects" that can be added to one character at a time.
Here is how it works:
drawField provide a text input box at x, y.
When a key is pressed we'll check to see if it is one of the following keys:
- ENTER
- BACKSPACE
- CODED
- a character (a, b, c, 1, 2, 3, !, @, #)
ENTER puts currentText into lastText and blanks the input field.
BACKSPACE removes the last character from currentText as long as it has at least one character.
CODED is ignored.
A character is added to currentText.
Here is what to do:
Add drawField(x, y) to setup(). x and y are ints that position the 16 by 70 text input field.
Add the drawField and keyPressed mthods to your own code.
// x and y position of text box
int x = 65, y = 90;
String lastInput = new String(); // final string
String currentInput = new String(); // string as it is typed in
void setup(){
size (200, 200);
smooth();
fill(255);
drawField(x, y);
}
void draw(){
}
void drawField(int xPos, int yPos){
fill(255);
rect (x, y, 70, 16);
}
void keyPressed() {
fill(0);
// run only when a key is pressed
if (key == ENTER) {
// the user presses ENTER telling us they have finished input
lastInput = currentInput;
currentInput = "";
drawField(x, y); // blank the text input field
}
else if (key == BACKSPACE && currentInput.length() > 0) {
// allows user to make corrections
currentInput = currentInput.substring(0, currentInput.length() - 1);
}
else if (key == CODED) {
// ignore...
}
else {
// build input one character at a time
currentInput = currentInput + key;
}
// The next line can be left out.
text(lastInput, x, y+30); // Shows input text
text(currentInput, x+3, y+12); // Shows text as it is typed in.
}