JavaFX apply Number Only Filter to StringProperty - Java JavaFX

Java examples for JavaFX:Bindable Properties

Description

JavaFX apply Number Only Filter to StringProperty

Demo Code


//package com.java2s;

import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;

import javafx.beans.value.ObservableValue;

public class Main {
    public static void applyNumberOnlyFilter(final StringProperty target,
            final int maxLength) {
        target.addListener(new ChangeListener<String>() {
            @Override//from   w  w  w .  ja  va2 s.  c  o m
            public void changed(
                    ObservableValue<? extends String> observableValue,
                    String oldValue, String newValue) {
                if (!(newValue.matches("\\d*") && newValue.length() <= maxLength)) {
                    target.set(oldValue);
                }
            }
        });
    }
}

Related Tutorials