gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:03:36 28 4
gpt4 key购买 nike

我正在尝试在 JavaFX 中制作数独游戏,但我不知道如何只允许输入一个字母。对此的答案是调用文本字段并执行以下操作:

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

上述方式不适用于复制粘贴......或大量其他东西等。使用这样的按键监听器似乎是一个糟糕的主意。一定有更好的吗?文本字段是否具有仅允许输入特定字符或仅允许输入特定数量字符的属性?

谢谢!

最佳答案

您可以使用 TextFormatter 去做这个。 TextFormatter如果文本字段具有与其关联的过滤器,则可以修改对文本字段中的文本所做的更改。过滤器是一个函数,它接受一个 TextFormatter.Change object 并返回相同类型的对象。可以返回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);

关于JavaFX TextField - 只允许输入一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34407694/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com