gpt4 book ai didi

java - 如何使用 JFormattedTextfield 接受字符串之类的名称?

转载 作者:行者123 更新时间:2023-11-29 08:50:47 26 4
gpt4 key购买 nike

如果我只想接受字母和空格,FormatterFactoryJFormattedTextField 中的因子值是多少。

因为我希望它只接受名称。喜欢 - John Doe

最佳答案

我找不到使用格式化程序的优雅方式。不优雅的方法是创建一个 MaskFormatter,主要问题是您将限制允许的字符数(尽管您可以限制为任意大的数字)。

MaskFormatter mask = new MaskFormatter("*************"); // Specifies the number of characters allowed.
mask.setValidCharacters("qwertyuiopasdfghjklzxcvbnm" +
" QWERTYUIOPASDFGHJKLZXCVBNM "); // Specifies the valid characters: a-z, A-Z and space.
mask.setPlaceholderCharacter(' '); // If the input is less characters than the mask, the space character will be used to fill the rest. Then you can use the trim method in String to get rid of them.
JFormattedTextField textField = new JFormattedTextField(mask);

我觉得在这种情况下验证输入是比限制字符更好的方法。如果您想使用这种方法,我可以添加一个示例。


编辑:使用InputVerifier,您必须对其进行子类化并覆盖verify,如下所示。

JTextField textField = new JTextField();
textField.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
if (text.matches("[a-zA-Z ]+")) // Reads: "Any of a-z or A-Z or space one or more times (together, not each)" ---> blank field or field containing anything other than those will return false.
return true;
return false;
}
});

在满足要求之前,文本字段不会产生焦点(父组件除外)。

关于java - 如何使用 JFormattedTextfield 接受字符串之类的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828689/

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