What is the recommended way to make a numeric TextField in JavaFX?

Harry Mitchell picture Harry Mitchell · Sep 26, 2011 · Viewed 141.5k times · Source

I need to restrict input into a TextField to integers. Any advice?

Answer

Evan Knowles picture Evan Knowles · Jun 12, 2015

Very old thread, but this seems neater and strips out non-numeric characters if pasted.

// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, 
        String newValue) {
        if (!newValue.matches("\\d*")) {
            textField.setText(newValue.replaceAll("[^\\d]", ""));
        }
    }
});