JavaFX TextField - 只允许输入一个字母 [英] JavaFX TextField - Allow only one letter to be typed

查看:244
本文介绍了JavaFX TextField - 只允许输入一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JavaFX中制作一个Suduko游戏,但我无法弄清楚如何只允许输入一个字母。这个问题的答案是调用textfield并执行:

I'm trying to make a Suduko game in JavaFX but I can't figure out how to only allow one letter to be entered. Would the answer to this to be to call the textfield and do:

myTextField.setOnKeyPressed(e ->
{
    if (!myTextField.getText().length().isEmpty())
    {
         // Somehow reject the key press?
    }
}

以上方式不适用于复制粘贴...或其他大量的东西等。使用像这样的关键新闻听众似乎是一个AWFUL的想法。必须有更好的东西吗?文本字段的属性是否只允许输入某些字符,或者只允许输入一定数量的字符?

The above way won't work with copy pasting... or tons of other things, etc. Using key press listeners like this seems like an AWFUL idea. There must be something better? Is there a property of text fields to allow only certain characters to be inputted, or only allow certain number of characters to be inputted?

谢谢!

推荐答案

您可以使用 TextFormatter 要做的事情如果 TextFormatter 可以修改文本字段中文本所做的更改(如果它有与之关联的过滤器)。 filter是一个函数,它接受一个 TextFormatter.Change 对象并返回一个相同类型的对象。它可以返回 null 来完全否决更改,或者修改它。

You can use a TextFormatter to do this. The TextFormatter can modify the changes that are made to the text in the text field if it has a filter associated with it. The filter is a function that takes a TextFormatter.Change object and returns an object of the same type. It can return null to veto the change entirely, or modify it.

所以你可以做到

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 ,并且只允许整数输入是有意义的。作为用户体验的最后补充,您可以修改更改,如果用户键入一个数字,它将替换当前内容(而不是在有太多字符时忽略它)。整个事情看起来像这样:

Note though that the TextFormatter can also be used to convert the text to a value of any type you like. In your case, it would make sense to convert the text to an Integer, and also to only allow integer input. As a final addition to the user experience, you can modify the change so that if the user types a digit, it replaces the current content (instead of ignoring it if there are too many characters). The whole thing would look like this:

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

这篇关于JavaFX TextField - 只允许输入一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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