0
   public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCancel) {
    System.exit(0);
}
if (e.getSource() == btnLogin) {
    int i = 0;
    while (loggedIn == false) {
        if (i < TeacherData.length) {
        if (txtUsername.getText() == TeacherData[i].getUsername() && String.valueOf(txtPassword.getPassword()) == TeacherData[i].getPassword()) {
                loggedIn = true;
                System.out.println("Login Successful");
            }
            else {
                System.out.println("Invalid Username or Password.");
                i++;
            }
        }
    }
}
}

My login panel is coded to look like this https://i.stack.imgur.com/cHoiP.jpg.

Upon pressing the "login", the button the console prints out "Invalid Username or Password." 10 times (there are 10 teachers in teacherData).

Before anybody asks I have already made sure the getUsername() and getPassword() methods work. txtUsername is the name of the JTextField and txtPassword is the name of the JPasswordField. I do not receive any errors.

Michael
  • 3,308
  • 5
  • 24
  • 36
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – guido Mar 13 '15 at 13:42

1 Answers1

0

change this line:

if (txtUsername.getText() == TeacherData[i].getUsername() && String.valueOf(txtPassword.getPassword()) == TeacherData[i].getPassword()) {

to this

String password = String.valueOf(txtPassword.getPassword());
if (txtUsername.getText().equals(TeacherData[i].getUsername()) && password.equals(TeacherData[i].getPassword())){

with == you compare the object references and not the values.

As result of this you will never login successfully.

btw. the String.valueOf is not necessary.

getPassword returns a char[] array. You have to convert it to String with: String.valueOf(txtPassword.getPassword())

nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • I did as you instructed and replaced the line in my code but the same problem persists. the console prints out "Invalid Username or Password" 10 times as opposed to printing out "Login Successful" 1 time. – Andres123 Mar 13 '15 at 16:44
  • @Andres123: what is txtPassword for a class? – nano_nano Mar 16 '15 at 08:30
  • txtPassword is a JPasswordField – Andres123 Mar 16 '15 at 12:17
  • @Andres123: see my updated answer. getPassword returns char[] and not String. First of all it must be converted. – nano_nano Mar 16 '15 at 14:05
  • Yes that is what the String.valueOf was for, i fixed my issue, i had used the String.valueOf on the String as opposed to the char value from the jpasswordfield. it was simply misplaced thanks for the assistance. – Andres123 Mar 18 '15 at 12:00