gpt4 book ai didi

java - 使用 DocumentFilter 过滤 JTextField 中的字符串、空格和点 (.)

转载 作者:行者123 更新时间:2023-11-30 03:27:47 26 4
gpt4 key购买 nike

我有一个 JTexTField,我希望用户输入一个人的名字。我认为该名称应包含 [a-zA-Z].space 示例 Mr.比尔。我正在使用 DocumentFilter 来验证用户输入。但是,我不知道应该如何在我的 DocumentFilter 中设置它。

问题:我应该如何修改过滤器才能实现上述行为?

任何有关如何验证个人姓名的建议都会被接受。

这是我的文档过滤器:

public class NameValidator extends DocumentFilter{
@Override
public void insertString(DocumentFilter.FilterBypass fp, int offset,
String string, AttributeSet aset) throws BadLocationException {
int len = string.length();
boolean isValidInteger = true;

for (int i = 0; i < len; i++) {
if (!Character.isLetter(string.charAt(i))) {
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.insertString(fp, offset, string, aset);
else {
JOptionPane.showMessageDialog(null,
"Please Valid Letters only.", "Invalid Input : ",
JOptionPane.ERROR_MESSAGE);
Toolkit.getDefaultToolkit().beep();
}
}

@Override
public void replace(DocumentFilter.FilterBypass fp, int offset, int length,
String string, AttributeSet aset) throws BadLocationException {
int len = string.length();
boolean isValidInteger = true;

for (int i = 0; i < len; i++) {
if (!Character.isLetter(string.charAt(i)) ) {
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.replace(fp, offset, length, string, aset);
else {
JOptionPane.showMessageDialog(null,
"Please Valid Letters only.", "Invalid Input : ",
JOptionPane.ERROR_MESSAGE);
Toolkit.getDefaultToolkit().beep();
}
}
}

这是我的测试类:

public class NameTest {

private JFrame frame;

public NameTest() {
frame = new JFrame();
initGui();
}

private void initGui() {

frame.setSize(100, 100);
frame.setVisible(true);
frame.setLayout(new GridLayout(2, 1, 5, 5));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField name = new JTextField(15);
((AbstractDocument) name.getDocument())
.setDocumentFilter(new NameValidator());
frame.add(name);

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
NameTest nt = new NameTest();

}
});
}
}

最佳答案

您可以将 JFormattedTextFieldMaskFormatter 一起使用。 MaskFormatter 允许您指定有效字符的String

MaskFormatter mf = new MaskFormatter( "***************" );
mf.setValidCharacters(" .abcABC");
JFormattedTextField ftf = new JFormattedTextField( mf );

格式化文本字段在幕后使用 DocumentFilter。阅读 Swing 教程中关于 How to Use Formatted Text Fields 的部分了解更多信息和示例。

您还可以尝试在论坛/网络中搜索正则表达式文档过滤器。这种类型的过滤器通常是可重用的,因为您只需要指定正则表达式。例如:Trouble using regex in DocumentFilter for JTextField

关于java - 使用 DocumentFilter 过滤 JTextField 中的字符串、空格和点 (.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776908/

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