Require the JavaFX text field to contain numeric digits only. - Java JavaFX

Java examples for JavaFX:TextField

Description

Require the JavaFX text field to contain numeric digits only.

Demo Code


//package com.java2s;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextField;

public class Main {
    /**//from w  w  w. j  a  v a 2 s. co m
     * Require the text field to contain numeric digits only.
     *
     * @param field the text field to restrict
     */
    public static void numericOnly(final TextField field) {
        field.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(
                    ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                if (!newValue.matches("\\d*")) {
                    field.setText(newValue.replaceAll("[^\\d]", ""));
                }
            }
        });
    }
}

Related Tutorials