On the Internet, I found very useful class, using which I can restrict TextField. I encountered a problem, where my TextField can contain only one '.' character. I suspect that I can handle this by writing an appripriate regex and set it as a restriction on the instance of that class. I use the following regex: "[0-9.-]", but it allows as many dots as the user types. May I ask you to help me to configure my TextField so that no more than one '.' is allowed.
import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.TextField; /** * Created by Anton on 7/14/2015. */ public class RestrictiveTextField extends TextField { private IntegerProperty maxLength = new SimpleIntegerProperty(this, "maxLength", -1); private StringProperty restrict = new SimpleStringProperty(this, "restrict"); public RestrictiveTextField() { super("0"); textProperty().addListener(new ChangeListener<String>() { private boolean ignore; @Override public void changed(ObservableValue<? extends String> observableValue, String s, String s1) { if (ignore || s1 == null) return; if (maxLength.get() > -1 && s1.length() > maxLength.get()) { ignore = true; setText(s1.substring(0, maxLength.get())); ignore = false; } if (restrict.get() != null && !restrict.get().equals("") && !s1.matches(restrict.get() + "*")) { ignore = true; setText(s); ignore = false; } } }); } /** * The max length property. * * @return The max length property. */ public IntegerProperty maxLengthProperty() { return maxLength; } /** * Gets the max length of the text field. * * @return The max length. */ public int getMaxLength() { return maxLength.get(); } /** * Sets the max length of the text field. * * @param maxLength The max length. */ public void setMaxLength(int maxLength) { this.maxLength.set(maxLength); } /** * The restrict property. * * @return The restrict property. */ public StringProperty restrictProperty() { return restrict; } /** * Gets a regular expression character class which restricts the user input. * * @return The regular expression. * @see #getRestrict() */ public String getRestrict() { return restrict.get(); } /** * Sets a regular expression character class which restricts the user input. * E.g. [0-9] only allows numeric values. * * @param restrict The regular expression. */ public void setRestrict(String restrict) { this.restrict.set(restrict); } }