0

My window is a login form which has 2 text fields (for user name and password) and 1 button (login button).

I used NetBeans to help me designing the window and this is the actionPerformed method for the login button:

private void loginButtonActionPerformed(ActionEvent evt) 
{   
    String password = new String(this.passwordField.getPassword());

    if (this.userNameTextField.getText() == "system" && password == "admin")
    {
        JOptionPane.showMessageDialog(null, "good");
    }

}  

I debugged the application because the login button did nothing and I found out that the if sentence was not even read. But if I remove the if sentence and press the login button, the message will appear.

What am I doing wrong ?

osos9
  • 117
  • 4
  • 1
    he he:). first of all you need to read swing tutorials.. that will help.. – subash Oct 24 '14 at 20:53
  • 2
    Don't compare Strings using `==`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *objects* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Oct 24 '14 at 20:57
  • Before you start building application with `Window Builder` you should first try to understand the concept behind the topic which you are implementing. – Vighanesh Gursale Oct 24 '14 at 20:58
  • 1
    And passwords should never be maintained in a String – MadProgrammer Oct 24 '14 at 21:17

2 Answers2

3

You are comparing strings using == operator, which is wrong.

Please us:

string1.equals(string2);

Relevant example:

password.equals("admin");
user2494817
  • 697
  • 4
  • 12
2

Strings should be compared with equals:

this.userNameTextField.getText().equals("system")

This will compare the text in the Strings.
What you are doing now is the comparison of references(i.e. where the Strings lie in memory)

And as mentioned in the comments: using JOptionPane.showMessageDialog(null, "good"); in an ActionListener is a bad idea as it block the whole GUI Thread

Dawnkeeper
  • 2,844
  • 1
  • 25
  • 41