Search code examples
javaswingjlabelequalsjtextfield

Why label.equals(label1) code doesn't sees label1?


what is wrong with my code? I'm taking input from JTextField passwordField/nickNameField to fieldNickname/fieldPassword and using for my registerAction. I've searched for answer but cant find.

My code takes input for nickname and password then asks for nickname and password. If true asks for nickname and password again on Login section.

I know problem source but idk what to do. That code must work without problem..

Problem source:

else if (trueNickname.equals(fieldNickname) && truePassword.equals(fieldPassword)) 

My code(Register section):

JLabel trueNickname = new JLabel("null");
JLabel truePassword = new JLabel("null");
JLabel fieldNickname = new JLabel (nickNameField.getText());
JLabel fieldPassword = new JLabel (passwordField.getText());

public void registerAction(ActionEvent e){
if (a == 0) {
    trueNickname.setText(nickNameField.getText());
    truePassword.setText(passwordField.getText());
    result.setText("Write your Nickname and Password again.");
    a = a + 1;
}
else if (trueNickname.equals(fieldNickname) && truePassword.equals(fieldPassword)) {
    result.setText("True Nickname and Password. You can login.");
}
else if (a == 1) {
    result.setText("SKIPPED(a = 1)");
}

}

On launch and using code, I'm getting "SKIPPED" as result.

Note: I'm new in stackoverflow so, sorry if i do something wrong.


Solution

  • To compare the text on the labels, you want to do trueNickname.getText().equals(fieldNickname.getText()).

    The equals method is a common pitfall because it takes an Object as a parameter. So the compiler lets you compare any objects even if it's a nonsensical comparison.