2

我有一个 Swing GUI,我在其中限制用户注册,以便用户名和密码不能相同。我正在使用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

4

4 回答 4

3

Replace

System.exit(0);

with

return;

if you do not want the rest of the method to be performed

于 2012-07-31T09:12:49.840 回答
3

You need to place your code within endless loop, and break it upon successful result. Something like:

while(true)
{
    // get input from user

    if(vlaidInput) break;
}
于 2012-07-31T09:13:59.093 回答
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
}
于 2012-07-31T09:26:29.083 回答
2

首先,最好将 UI 和业务逻辑(在本例中为验证)分开。让他们单独提出一种更好的方式来单独处理交互。UserValidation因此,使用方法创建一个单独的类是有意义的boolean isValid()。像这样的东西:

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)逻辑的职责。

于 2012-07-31T09:57:52.373 回答