如何控制 Javafx Textfield 输入使其不接受 space

how to control Javafx Textfield input so it wont accept space

我在 JavaFX 中创建了一个用户名文本字段,我想要 运行 一种检查是否存在 space 的方法! , 有办法吗?

TextFormatter 的过滤器

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;
}));