我想创建一个简单的程序来演示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!");
}
}
}
答案 0 :(得分:1)
您需要使用.equals()字符串方法,因此请更改
if(userAttempt == correctPW) {
到
if(userAttempt.equals(correctPW)) {
==检查它是否是同一个对象(在内存中).equals()检查它们是否具有相同的值(有关此差异的详细信息,请参阅What is the difference between == vs equals() in Java?)