How to specify a number input range in a controlP5 textField?

721 Views Asked by At

Specifically, how do I prevent input when the first character is , and 0 in a textField? The controlP5 filter did not work. public void keyPressed (KeyEvent e) { int key = e.getKeyCode(); if (key => 5 && key <= 25) e.setKeyChar('' ... //x10.setText ? How to make a number input range from in a textField How to prevent input by the first character "," and "0" in textField. if (points> = 5 && points <= 25) {example the Controlp5 library did not work. http://www.sojamo.de/libraries/controlP5/reference/controlP5/Textfield.InputFilter.html.

1

There are 1 best solutions below

0
On BEST ANSWER

The code below is what you want -- put it at the end of draw() (rather than keyPressed() because keyPressed() is called before controlP5 consumes the key event).

However, what you're asking for is problematic. You want to validate the number as the user types in input, and not after the input is fully entered. This leads to a problem: suppose they wish to type in "15"; they first type "1", but this will be rejected because it is not within the correct range (5-25). It would be better to validate input after it is fully entered (when the enter key is pressed for example), or use slider or knob instead.

if (keyPressed && textField.isFocus()) {
    float n;
    try {
        n = Float.parseFloat(textField.getText().replace(',', '.')); // may throw exception
        if (!(n >= 5 && n <= 25)) {
            throw new NumberFormatException(); // throw to catch below
        }

    } catch (Exception e2) {
        String t;
        if (textField.getText().length() > 1) {
            t = textField.getText().substring(0, textField.getText().length() - 1);
        } else {
            t = "";
        }
        textField.setText(t);
    }
}