2012-07-31 43 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)逻辑的责任。