GYBE :
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 number into TextField
. Therefore the range should be from 0x0000 to 0x3FFF. I have already built my GUI via SceneBuilder
, therefore I just need a function to handle restriction and conversion on user's input.
EDIT
This is my version:
startAddressField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("^[0-9A-F]?")) {
startAddressField.setText(oldValue);
}
});
fabian :
Use a TextFormatter
with UnaryOperator
and StringConverter<Integer>
as shown below:
UnaryOperator<TextFormatter.Change> filter = change -> change.getControlNewText().matches("[0-3]?\\p{XDigit}{0,3}") ? change : null;
StringConverter<Integer> converter = new StringConverter<Integer>() {
@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<Integer> 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.