下面给出的代码对一个 JTextField 进行实时验证。在输入一些值以txt1
启用保存按钮并删除值时,将保存按钮重置为禁用。我使用 Netbeans 作为 IDE。
我的 Swing 应用程序几乎没有 JTextField。我想要做的是,在检查多个 JTextFields 的有效性后启用保存按钮。如果任何文本字段为空,则btnSave
必须禁用。
有人可以帮助我扩展这个程序来验证多个 JTextFields 吗?
public NewJFrame() {
initComponents();
btnSave.setEnabled(false);
txt1.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void removeUpdate(DocumentEvent e) {
validate(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
if (currText.isEmpty()) {
Runnable doRun = new Runnable() {
@Override
public void run() {
isValidFromTextField1 = false;
validFormatterLimit();
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
@Override
public void run() {
isValidFromTextField1 = true;
validFormatterLimit();
}
};
SwingUtilities.invokeLater(doRun);
}
}
});
txt2.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void removeUpdate(DocumentEvent e) {
validate(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
if (currText.isEmpty()) {
Runnable doRun = new Runnable() {
@Override
public void run() {
isValidFromTextField2 = false;
validFormatterLimit();
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
@Override
public void run() {
isValidFromTextField2 = true;
validFormatterLimit();
}
};
SwingUtilities.invokeLater(doRun);
}
}
});
}
public void validFormatterLimit() {
if (isValidFromTextField1 == true && isValidFromTextField2 == true) {
btnSave.setEnabled(true);
} else {
btnSave.setEnabled(false);
}
}