1
下面給出的代碼對一個JTextField進行實時驗證。輸入一些值到txt1
啓用保存按鈕並刪除值將重置保存按鈕以禁用。我使用Netbeans作爲IDE。添加DocumentListener以驗證多個JTextField
我的Swing應用程序有幾個JTextFields。我想要做的是在檢查多個JTextField的有效性後啓用Save按鈕。如果任何文本字段爲空,則必須禁用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);
}
}
Thnx快速響應。我會檢查一下並讓你知道。 – amal 2013-04-22 08:25:46
thnx很多。它完美的作品。 – amal 2013-04-22 09:58:15
不用客氣 – mKorbel 2013-04-22 10:14:46