Search code examples
javaswingjpasswordfield

Why is my password validation not working Java?


I have a password field in my login screen. For some reason when i type in the correct password which is "u123" it gives me the incorrect password error message even though it is correct. Why is it doing this.

The code i have below:

btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            char[] userInput = passwordField.getPassword();
            char[] correctPassword = { 'u', '1', '2', '3'};

            if (userInput.equals(correctPassword)) {
            JOptionPane.showMessageDialog(LoginScreen.this,
                    "Success! You typed the right password.");
            } else {
                JOptionPane.showMessageDialog(LoginScreen.this,
                    "Invalid password. Try again.",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    });

I know this may not be the best way of doing the password check but I'm just a beginner and just trying to get some practice.


Solution

  • Your code has :

    char[] userInput = passwordField.getPassword();
    char[] correctPassword = { 'u', '1', '2', '3'};
    

    It's two different arrays of characters.

    So this test returns false :

     if (userInput.equals(correctPassword))
    

    Instead, try to use the Arrays.equals() method

     if (Arrays.equals(userInput, correctPassword)) { ... }