Domanda

I'm fairy new to Java so I don't even know if I'm doing this correctly but I have created a GUI with a text field, a password field and button. I have an event listener on the button. When it's pressed, the listener will check the name and password fields but it is currently not working as intended.

Event code:

public class event implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent arg) {
        String name = textfield.getText();
        char[] temp_pass = password.getPassword();
        String pass = new String(temp_pass);

        if (name == "Spedwards" && pass == "test") {
            result.setText("Welcome Liam");
        } else {
            result.setText("Unknown User");
        }
    }
}

The way I understand this, is it gets the text from the text field and the password field then checks to see if it equals Spedwards and test respectively, then sets the text for the label I have on the GUI. Currently however, it only sets the text as Unknown User regardless of putting in the correct information or not.

Why does it do this and how can I correctly get the values I need?

È stato utile?

Soluzione

As already mentioned in comments. The secure way to compare Strings is using String.equals() method

Change the line

if (name == "Spedwards" && pass == "test") {

to

if ("Spedwards".equals(name) && "test".equals(pass)) {

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top