Restricting a TextField input to hexadecimal values in Java FX

后端 未结 3 1843
Happy的楠姐
Happy的楠姐 2021-01-21 20:37

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

3条回答
  •  猫巷女王i
    2021-01-21 21:24

    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.

提交回复
热议问题