如何在中途停止按钮ActionListener并等待用户再次单击它?

问题描述 投票:0回答:2

我真的需要解决这个问题,即使经过2个小时的搜索也没有找到解决方案。我正在通过开发简单的应用程序来学习Java AWT。

我创建了一个注册页面/窗口/框架,它通过各自的TextFields获取用户名,密码和确认密码,并在单击“注册”按钮时将它们添加到数据库中,当且仅当两个密码时比赛。如果它们不匹配,则清除密码文本字段,用户需要重新输入值并再次单击“注册”按钮。这需要循环进行。我已将所有必需代码行(包括密码不相等的逻辑)放在“注册”按钮的ActionListener中。

我发布了代码中按钮的ActionListener部分。您会注意到明显的逻辑错误,例如,在使用setText("")清除密码的TextField后,密码实际匹配,因为两者都是空字符串。但是,即使我只清除了两个TextField中的一个,一旦执行了ActionListener,我就无法在TextFields中重新输入新值,应用程序会永久挂起,直到强制关闭。

signupButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {               
        String username = "";
        String password = "";
        String confirmPass = "";

        do
        {
            username = usernameTF.getText();
            password = passwordTF.getText();
            confirmPass = confirmPassTF.getText();

            Label passErrorMsg = new Label("Passwords do not match. Enter again.");

            if(password.equals(confirmPass))
            {
                passErrorMsg.setVisible(false);
                break;
            }

            passErrorMsg.setBounds(70, 320, 205, 20);
            signupWindow.add(passErrorMsg);
            passErrorMsg.setVisible(true);

            passwordTF.setText(""); //If I comment this statement, the app hangs.
            //Else in the next iteration, the loop breaks since both the strings become empty

            confirmPassTF.setText("");

        }while(true);

       //Some more lines of code to work with the database
    }
});
java awt actionlistener
2个回答
2
投票

你的while循环不属于,因为它适用于线性控制台程序,会阻止事件驱动程序中的Swing事件线程或任何其他事件线程,使程序冻结和无用。相反,如果输入错误,您可能只想清除对话框的文本字段,并在JOptionPane中显示错误消息。事实上,你可能只需要if / else块而不是while循环:

SignupButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {               
        String Username = "";
        String Password = "";
        String ConfirmPass = "";

        Username = UsernameTF.getText();
        Password = PasswordTF.getText();
        ConfirmPass = ConfirmPassTF.getText();

        if(Password.equals(ConfirmPass)) {
            PassErrorMsg.setVisible(false);

            // do database stuff here

        } else {
            // here clear fields and show an error message
            // consider incrementing an error count as well
        }
    }
});

同样关键的问题是,在创建事件驱动程序时,您必须以非线性事件驱动的方式进行思考。线性控制台代码逻辑不起作用(在这些情况下)。

其他问题:你不应该使用字符串来保存密码,因为这些将被插入到字符串池中可以很容易地被黑客攻击。此外,是的,如Camickr所述,学习并遵循Java命名约定,包括使用小写字母和带有大写字母的类名称启动变量和方法名称。避免使用setBounds(...)null布局,因为这些布局导致GUI在所有平台上都无法正常工作。而是学习和使用布局管理器。


0
投票

如果函数/方法只能在按钮单击时触发一次,则不应该进行迭代 - 上面的代码可能最终会以无限循环结束。

© www.soinside.com 2019 - 2024. All rights reserved.