Search code examples
javaswingjlabeljtextfield

JTextField string not working


I want to create a simple program to demonstrate GridLayout, but for some reason the string from the JTextField doesn't seem to ever match the password, even if I type it right. I tried a bunch of things like get the substring in case the textfield included the spaces but the label keeps saying "incorrect".

// test gridlayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GaoGridLayout implements ActionListener {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GaoGridLayout pwChecker = new GaoGridLayout();
    }
    // declare variables
    private final String correctPW = "lol";

    private JFrame frame;
    private JTextField pwField;
    private JLabel pwLabel;
    private JButton attemptPW;

    public GaoGridLayout() {
        // initialize variables
        pwField = new JTextField(8);
        pwLabel = new JLabel("Enter the password");
        attemptPW = new JButton("Confirm Attempt");

        // attach GUI as event listener to attemptPW button
        attemptPW.addActionListener(this);

        // ~~~~~~~~~~ create the layout ~~~~~~~~~~
        JPanel north = new JPanel(new GridLayout(1,2));
        north.add(new JLabel("Password"));
        north.add(pwField);

        // entire window
        frame = new JFrame("Password Checker");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(north, BorderLayout.NORTH);
        frame.add(pwLabel, BorderLayout.CENTER);
        frame.add(attemptPW, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);

    }
    // what to do when user clicks the button
    @Override
    public void actionPerformed(ActionEvent event) {
        // if password is correct or not
        String userAttempt = pwField.getText().substring(0, 3);

        System.out.println(userAttempt);
        System.out.println(userAttempt.charAt(2));

        if(userAttempt == correctPW) {
            pwLabel.setText("Correct!");
        } 
        else {
            pwLabel.setText("Incorrect!");
        }
    }

}

Solution

  • You need to use the .equals() string method so change

    if(userAttempt == correctPW) {
    

    to

    if(userAttempt.equals(correctPW)) {
    

    == checks if it is the same object (in memory) .equals() checks if they have the same value (see What is the difference between == vs equals() in Java? for more in depth detail on this difference)