Search code examples
javafxfxml

how to control Javafx Textfield input so it wont accept space


I made a textfield in JavaFX of username, I want to run a method that checks if there is a space or not! , is there a way to do that ?


Solution

  • TextFormatter's filter

    This filter(UnaryOperator) allows a user to intercept and modify any change done to the text content. Here is an example which sets no change on space value.

    TextField field = new TextField();
    
    field.setTextFormatter(new TextFormatter<>(change -> {
        if (change.getText().equals(" ")) {
            change.setText("");
        }
        return change;
    }));