目前我在每个文本字段上使用 DocumentListener 来实时验证用户输入,但我认为必须有更聪明的方法,因为我重复了这么多。
有没有更聪明的方法?
nameJTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
validateName(nameJTextField.getText());
}
@Override
public void removeUpdate(DocumentEvent e) {
validateName(nameJTextField.getText());
}
@Override
public void changedUpdate(DocumentEvent e) {
}
private void validateName(String name) {
if (name.matches("^[A-ZÆØÅa-zæøå0-9]{2,40}$")) {
errorNameJLabel.setText("");
} else {
errorNameJLabel.setText("Min 2 and max 40 letters and numbers");
}
}
});
最佳答案
since I am repeating my self so much.
创建一个可以添加到任何文本字段的通用 DocumentListener 即:
- 应在 DocumentListener 中定义 validateName(...) 方法
- 不要使用文本字段来获取文本。相反,您可以从文档中获取文本。 DocumentEvent 具有对 Document 的引用。
此外,您不会在 changedUpdate(...) 方法中进行验证。该方法仅用于在使用 JTextPane 或 JEditorPane 时更改文本中的属性(字体、颜色等)。
在不知道您的验证细节的情况下,很难给出更具体的答案。
关于java - 使用 Java DocumentListener 的更智能方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264880/