The forum discussion linked by @EnhancedLoop7 is no longer valid and the programmer must not attempt to change the value displayed in a textfield or textarea control while it has focus it will crash the sketch). This means that it is not possible to constrain the textfield input to an integer by ignoring non-numeric characters.
Instead we can test the input as it changes and give a visual warning if invalid.
The sketch below has a single GTextField control and the text colour changes to red when the input value is not an integer and black when OK. The event handler code can easily be modified to perform other types of validation e.g. accepting float values only…
/**
Sketch to demonstrate how to check that the input of a GTextField
is an integer.
When the textfield has focus the input value is tested everytime
it changes (e.g. when a key is pressed.
If the input is a valid integer the text remains black but when
invalid the text is red.
NOTE: you must not programatically modify the textfiled input
value while the control has focus.
created by Peter Lager 2018
*/
import g4p_controls.*;
GTextField txf; // the text field we want to enter an interger
int n; // the last valid integer entered.
void setup() {
size(300, 200);
txf = new GTextField(this, 20, 30, 200, 20);
}
void draw() {
background(200, 200, 255);
}
void handleTextEvents(GEditableTextControl textcontrol, GEvent event) {
if (textcontrol == txf) {
if (event == GEvent.CHANGED) {
try {
n = Integer.parseInt(txf.getText());
txf.setLocalColor(2, color(0));
}
catch(java.lang.NumberFormatException e) {
txf.setLocalColor(2, color(255, 0, 0));
}
}
}
}