在Java FX中将TextField输入限制为十六进制值 [英] Restricting a TextField input to hexadecimal values in Java FX

查看:142
本文介绍了在Java FX中将TextField输入限制为十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将用户的输入限制为仅十六进制值? 使用十进制表示法时,范围是从0到16383,但是我想让用户在TextField中键入一个十六进制数.因此,范围应从 0x0000 0x3FFF .我已经通过SceneBuilder构建了我的GUI,因此我只需要一个函数来处理对用户输入的限制和转换.

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.

编辑

这是我的版本:

startAddressField.textProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue.matches("^[0-9A-F]?")) {
            startAddressField.setText(oldValue);
        }
    });

推荐答案

使用带有UnaryOperatorStringConverter<Integer>TextFormatter,如下所示:

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);

可通过TextFormatter.value属性获得转换后的值.仅在按Enter或TextField失去焦点时才会更新.

The converted value is available via TextFormatter.value property. It only gets updated on pressing enter or the TextField loosing focus.

这篇关于在Java FX中将TextField输入限制为十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆