How can I restrict the input from the user to only hexadecimal values? With decimal notation the range is from 0 to 16383, but I would like to let the user type an hexadecimal n
Use a TextFormatter with UnaryOperator and StringConverter as shown below:
UnaryOperator filter = change -> change.getControlNewText().matches("[0-3]?\\p{XDigit}{0,3}") ? change : null;
StringConverter converter = new StringConverter() {
@Override
public String toString(Integer object) {
return object == null ? "" : Integer.toHexString(object);
}
@Override
public Integer fromString(String string) {
return string == null || string.isEmpty() ? null : Integer.parseInt(string, 16);
}
};
TextFormatter formatter = new TextFormatter<>(converter, null, filter);
textField.setTextFormatter(formatter);
The converted value is available via TextFormatter.value property. It only gets updated on pressing enter or the TextField loosing focus.