javaprocessingcontrol-p5

Blacklisting characters in a controlP5 textField


In the controlP5 library, I need to prohibit certain characters from being entered into a textField.

I found a piece of code where you indicate what to prohibit, but I don’t know how to enforce the conditions (possibly by emulating the erase button?).

This is what I'd like to whitelist:enter image description here


Solution

  • ControlP5 provides built-in whitelist filters for numbers: integers (0-9) and floats (which is integers and .):

    textField.setInputFilter(ControlP5.INTEGER);

    textField.setInputFilter(ControlP5.FLOAT);

    Looking at your screenshot, it seems you want to whitelist , too. Custom filters are not possible, even when extending the Textfield class due to how the class is setup (the critical members are protected or private).

    So that leaves you with this indirect option to additionally whitelist ,:

    @Override
    public void keyPressed(KeyEvent event) {
        if (event.getKey() == ',') {
            textField.setText(textField.getText() + ',');
        }
    }
    

    , is whitelisted by appending it to the textfield's current text when Processing detects the correct key pressed event.