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

时间:2015-12-22 02:46:36

标签: user-interface javafx textfield

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用TextFormatter执行此操作。如果{1}}具有与之关联的过滤器,则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);
相关问题