2012-07-31 41 views
2

我有一個Swing GUI,我限制用戶註冊,以便用戶名和密碼不能相同。我使用JoptionPane的任務用下面的代碼:JoptionPane驗證

public void actionPerformed(ActionEvent e) { 
String username = tuser.getText(); 
String password1 = pass1.getText(); 
String password2 = pass2.getText(); 
String workclass = wclass.getText(); 
Connection conn = null; 

try { 
    if(username.equalsIgnoreCase(password1)) { 
     JOptionPane.showMessageDialog(null, 
      "Username and Password Cannot be the same. Click OK to Continue", 
      "Error", JOptionPane.ERROR_MESSAGE); 
     System.exit(0); 
    } 
... 

的問題是,我不得不使用System.exit(0);沒有它,下一個代碼被執行。即使在JOptionPane猛增之後,註冊仍然成功。我不需要系統退出,但我需要用戶在驗證後保存在註冊頁面上。做這個的最好方式是什麼?有沒有其他方便的方法來做到這一點,而不是使用JOptionPane

回答

3

更換

System.exit(0); 

return; 

,如果你不想被執行

+0

我認爲這是最好的選擇,因爲它避免了循環會產生的無用負載。 – 2012-07-31 09:52:00

+0

我完全同意你的SoboLan。它工作得很好......我想要的方式。 – ErrorNotFoundException 2012-07-31 10:01:51

3

您需要將無限循環中您的代碼的方法的其餘部分做的,打破它取得成功的結果。喜歡的東西:

while(true) 
{ 
    // get input from user 

    if(vlaidInput) break; 
} 
3

地方,下面的代碼到其他部分可能是它的工作原理

if(username.equalsIgnoreCase(password1)) 
{ 
    JOptionPane.showMessageDialog(null, "Username and Password Cannot be the same. Click OK to Continue","Error",JOptionPane.ERROR_MESSAGE); 

} 
else 
{ 
    //place that next code 
    // username and password not equals, then it will execute the code 
} 
2

首先,它是最好的,如果在UI和業務邏輯(在這種情況下,驗證)分離。讓他們單獨提出一種更好的自行處理交互方式。因此,使用方法boolean isValid()創建單獨的類UserValidation是有意義的。事情是這樣的:

public class UserValidation { 
    private final String name; 
    private final String passwd; 
    private final String passwdRpt; 

    public UserValidation(final String name, final String passwd, final String passwdRpt) { 
     this.name = name; 
     this.passwd = passwd; 
     this.passwdRpt = passwdRpt; 
    } 

    public boolean isValid() { 
     // do your validation logic and return true if successful, or false otherwise 
    } 
} 

隨後的動作代碼是這樣的:

public void actionPerformed(ActionEvent e) { 
     if (new UserValidation(tuser.getText(), pass1.getText(), pass2.getText()).isValid()) { 
      // do everything needed is validation passes, which should include closing of the frame of dialog used for entering credentials. 
     } 

     // else update the UI with appropriate error message -- the dialog would not close by itself and would keep prompting user for a valid entry 
} 

建議的方法給你一個方法可以輕鬆地進行單元測試驗證邏輯,並在不同情況下使用它。另請注意,如果方法isValid()中的邏輯比應該由SwingWorker執行的邏輯大。 SwingWorker的調用是動作(即UI)邏輯的責任。