栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaFX TextField-只允许输入一个字母

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaFX TextField-只允许输入一个字母

您可以使用

TextFormatter
来执行此操作。该
TextFormatter
可以修改都在文本字段做,如果有一个与之关联的过滤器的变化。过滤器是接受
TextFormatter.Change
对象并返回相同类型的对象的函数。它可以
null
完全否决更改,也可以对其进行修改。

所以你可以做

TextField textField = new TextField();textField.setTextFormatter(new TextFormatter<String>((Change change) -> {    String newText = change.getControlNewText();    if (newText.length() > 1) {        return null ;    } else {        return change ;    }});

请注意,尽管

TextFormatter
也可以使用将该文本转换为您喜欢的任何类型的值。在您的情况下,将文本转换为
Integer
,并且仅允许整数输入是有意义的。作为最终的用户体验,您可以修改更改,以便如果用户键入数字,它将替换当前内容(如果字符太多,则不要忽略它)。整个过程看起来像这样:

    TextField textField = new TextField();    // converter that converts text to Integers, and vice-versa:    StringConverter<Integer> stringConverter = new StringConverter<Integer>() {        @Override        public String toString(Integer object) { if (object == null || object.intValue() == 0) {     return ""; } return object.toString() ;        }        @Override        public Integer fromString(String string) { if (string == null || string.isEmpty()) {     return 0 ; } return Integer.parseInt(string);        }    };    // filter only allows digits, and ensures only one digit the text field:    UnaryOperator<Change> textFilter = c -> {        // if text is a single digit, replace current text with it:         if (c.getText().matches("[1-9]")) { c.setRange(0, textField.getText().length()); return c ;        } else         // if not adding any text (delete or selection change), accept as is if (c.getText().isEmpty()) { return c ;        }        // otherwise veto change        return null ;    };    TextFormatter<Integer> formatter = new TextFormatter<Integer>(stringConverter, 0, textFilter);    formatter.valueProperty().addListener((obs, oldValue, newValue) -> {        // whatever you need to do here when the actual value changes:        int old = oldValue.intValue();        int updated = newValue.intValue();        System.out.println("Value changed from " + old + " to " + new);    });    textField.setTextFormatter(formatter);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号