I am looking for an alternative of Swing InputVerifier to JavaFX TextField.
The Swing InputVerifier will prevent input that does verify.
Consider the following S
I have IntegerField control with StringConverter, UnaryOperator and TextFormatter. Maybe helpful for you!
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.util.StringConverter;
import javafx.util.converter.IntegerStringConverter;
import java.util.function.UnaryOperator;
public class IntegerField extends TextField {
public IntegerField() {
super();
StringConverter<Integer> integerStringConverter = new IntegerStringConverter();
UnaryOperator<TextFormatter.Change> filter = getFilter();
setTextFormatter(new TextFormatter<>(integerStringConverter, null, filter));
setOnAction(event -> integerStringConverter.fromString(this.getText()));
}
private UnaryOperator<TextFormatter.Change> getFilter() {
return change -> {
String text = change.getText();
if (!change.isContentChange()) {
return change;
}
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
}
public Integer getValue() {
return Integer.valueOf(this.getText());
}
}
As first suggested by James_D a TextFormatter with filter was the solution.
TextField instance = new TextField();
UnaryOperator<Change> textFilter = change -> {
String input = change.getText();
if (!change.isContentChange()) {
return change;
}
if (!myRegExTool.matches(input)) {
return null;
}
return change;
};
instance.setTextFormatter(new TextFormatter<String>(textFilter));