我想让用户只能输入3位数字。
我尝试使用 [0,9]{0,3} 来确保输入不能超过 3 位数字,但是,[0,9] 部分有效,我无法输入像 abcd 这样的东西,但是{0,3}部分不起作用,我可以输入 3 个以上的数字,例如 123456
TextField textArea1 = new TextField();
textArea1.setTextFormatter(new TextFormatter<String>(new UnaryOperator<TextFormatter.Change>() {
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
String value = change.getText();
if(value.matches("[0-9]{0,3}"))
{
return change;
}
return null;
}
}));
最佳答案
如果更改为零或多个数字且控件的文本长度小于或等于 3,则返回更改。
TextField textArea1 = new TextField();
UnaryOperator<Change> integerFilter = change -> {
System.out.println(change);
if (change.getText().matches("\\d*") && change.getControlNewText().length() <= 3) {
return change;
}
return null;
};
如果您只想使用Matches
,则需要使用getControlNewText()
。
TextField textArea1 = new TextField();
UnaryOperator<Change> integerFilter = change -> {
System.out.println(change);
if (change.getControlNewText().matches("[0-9]{0,3}")) {
return change;
}
return null;
};
关于java - 我想让一个文本字段限制 3 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57774454/