java - JTextField 字符串不起作用

标签 java swing jlabel jtextfield

我想创建一个简单的程序来演示 GridLayout ,但由于某种原因来自 JTextField 的字符串似乎与密码不匹配,即使我输入正确。我尝试了很多方法,例如获取子字符串,以防文本字段包含空格,但标签一直显示“不正确”。

// 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?)

关于java - JTextField 字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49681528/

相关文章:

java - ThreadMXBean.getThreadAllocationBytes(long id) 中包含哪些 JVM 运行时数据区域

java - MapStruct - 找不到实现

java - 有没有办法在 JDatePicker 上设置日期值

java - "Global"文本输入中的热键除外

java - 以动态方式在 JScrollPane 上插入面板

java - 单击 Jbutton 后如何显示/隐藏附加到 Jlabel 的图像?

java - 在 Oracle 中设置时间戳

java - 当/否则语句多个条件时出现 JSTL 错误

java - 在另一个 JLabel 前面显示一个 JLabel

java - 如何刷新我的 JLabel 图标?