我正在製作一個swing MVC應用程序,以瞭解使用Swing Framework進行的GUI設計的複雜性。我的JDK版本是7,我有一個簡單的應用程序,其中包含一個對話框,其中包含用於存儲文件路徑的文本框,瀏覽按鈕,用於用戶標識和密碼的2個文本框以及用於更新和取消功能的2個按鈕。MVC應用程序中的DocumentListener驗證錯誤
單擊這些按鈕只是顯示一個對話框,其上帶有更新或取消消息。
我計劃使用DocumentListener來驗證textfield組件。
在UI我有以下代碼來創建2個文本框:
public JPasswordField getMyPasswordField() {
if(myPasswordField == null)
{
myPasswordField = new JPasswordField();
myPasswordField.setBounds(133, 93, 163, 21);
myPasswordField.getDocument().putProperty("Owner", "myPasswordField");
}
return myPasswordField;
}
public JTextField getMyUserNameField() {
if(myUserNameField== null)
{
myUserNameField = new JTextField();
myUserNameField.setBounds(133, 66, 163, 21);
myUserNameField.getDocument().putProperty("Owner", "myUserNameField");
}
return myUserNameField;
}
在我用下面的代碼,所述控制器:
myReferenceUI.getMyUserNameField().getDocument().addDocumentListener(this);
myReferenceUI.getMyPasswordField().getDocument().addDocumentListener(this);
而在方法實現我寫了下面:
public void insertUpdate(DocumentEvent e) {
Object owner = e.getDocument().getProperty("Owner");
changed(owner);
}
@Override
public void removeUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
@Override
public void changedUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
public void changed(Object e)
{
System.out.println(e.toString());
if( e.toString().equals("myUserNameField"))
{
if(myReferenceUI.getMyUserNameField().getText().equals(""))
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
if( e.toString().equals("myPasswordField"))
{
if(myReferenceUI.getMyPasswordField().getText().equals(""))
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
myReferenceUI.getMyUpdateButton().setEnabled(true);
}
我的意圖是僅當用於用戶名和密碼的2個文本框具有非空值時啓用更新按鈕。
偵聽器事件正確觸發,並且在用戶名/密碼字段中輸入空值時禁用更新按鈕。
但是,在這些字段中輸入任何值後,如果我按退格鍵並擦除文本,更新按鈕將保持禁用狀態。
我該如何擺脫這種情況?
你是什麼意思由空條目? – Sage
@Sage這是指用戶名/密碼字段中的任一個爲空 – user2991608