JTextField 字符串不起作用

JTextField string not working

我想创建一个简单的程序来演示 GridLayout,但由于某些原因,JTextField 中的字符串似乎与密码不匹配,即使我输入正确也是如此。我尝试了很多方法,比如获取子字符串,以防文本字段包含空格,但标签一直显示 "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!");
        }
    }

}

你需要使用 .equals() 字符串方法所以改变

if(userAttempt == correctPW) {

if(userAttempt.equals(correctPW)) {

== 检查它是否是同一对象(在内存中)。equals() 检查它们是否具有相同的值(有关此差异的更多详细信息,请参阅 What is the difference between == vs equals() in Java?