我正在为一个学校项目制作密码保险库,我正在尝试将“masterPassword”与“enteredPassword”进行比较,但每当我测试“enteredPassword”时,它都会作为空变量返回。我该如何解决?
我试过注释掉代码 actionListener 并让它简单地 showConfirmDialog(null,enteredPassword) 并返回空白。
import java.awt.*;
import java.awt.event.*;
public class PasswordVault implements ActionListener
{
static String masterPassword;
static String enteredPassword;
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("What is your name?");
masterPassword = JOptionPane.showInputDialog("Hello, " + name + ". " + "What would you like your master password to be?");
new PasswordVault();
}
public PasswordVault()
{
JFrame masterPasswordFrame = new JFrame("Master Password");
masterPasswordFrame.setSize(400,100);
masterPasswordFrame.setLocation(500,300);
masterPasswordFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
JPasswordField masterPasswordField = new JPasswordField(10);
masterPasswordField.setEchoChar('*');
JLabel passwordLabel = new JLabel("Enter Password: ");
JButton okayButton = new JButton("Check");
okayButton.addActionListener(this);
mainPanel.add(passwordLabel);
mainPanel.add(masterPasswordField);
mainPanel.add(okayButton);
masterPasswordFrame.add(mainPanel);
masterPasswordFrame.setVisible(true);
masterPasswordFrame.pack();
enteredPassword = new String(masterPasswordField.getPassword());
}
public void actionPerformed(ActionEvent event)
{
if(enteredPassword.equals(masterPassword))
{
JOptionPane.showConfirmDialog(null, "Correct");
//close the masterPasswordFrame and take the user to the Password Vault
}
else
{
JOptionPane.showConfirmDialog(null, "Password Incorrect. Please Try Again.");
}
}
}
我希望代码输出输入的密码是否与主密码匹配,但它不输出任何内容。