Search code examples
javaarraysjtextfield

Comparing JTextField value to multiple arrays


I started learning Java recently so I decided to make a simple sign up/log in form.

private JTextField username;
private JPasswordField password;
private JButton check;
private JButton addToDb;
ArrayList<String> dbUser = new ArrayList<String>();
ArrayList<String> dbPassword = new ArrayList<String>();

public trial(){
    super("Title");
    setLayout(new FlowLayout());

    username = new JTextField("",10);
    password = new JPasswordField("",10);
    check = new JButton("Login");
    addToDb = new JButton("Sign Up");
    add(username);
    add(password);
    add(check);
    add(addToDb);

    addToDb.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    if(!username.getText().isEmpty()
                        && !password.getText().isEmpty()){

                        dbUser.add(username.getText());
                        dbPassword.add(password.getText());
                        username.setText("");
                        password.setText("");
                        System.out.println(dbUser + "/" + dbPassword);

                    }else{

                        System.out.println("Please fill the fields and try again!");
                    }
                }
            }               
    );

    check.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){

                    for(int i=0; i<dbUser.size();i++){

                        if(username.getText() == dbUser.get(i) && password.getText()== dbPassword.get(i)){
                            JOptionPane.showMessageDialog(null, "Access Granted!");
                        }else{
                            JOptionPane.showMessageDialog(null, "Access Denied!");
                        }                       
                    break;                          
                    }
                }
            }
    );                      
  }
}

As you can see, I've made two text fields (username and password), two buttons, one that stores the values in two different arraylists (I tried with a HashMap but that didn't work either). And one that compares the values in the arrays to the values in the text fields. The problem is that when I use the login button, it always says access denied. Any ideas how to fix this?


Solution

  • In java Strings are compared with equals and not ==. The reason is, strings are objects and not primitives. See What is the difference between == vs equals() in Java? for more information about == and equals()

    So the if expression is wrong:

    username.getText().equals(dbUser.get(i)) && password.getText().equals( dbPassword.get(i))