我正在为一个学校项目制作一个密码库,并且试图将“ masterPassword”与“ enteredPassword”进行比较,但是每当我测试“ enteredPassword”时,它将作为空变量返回。我该如何解决?
我尝试注释掉代码actionListener,让它只是showConfirmDialog(null,enterpassword),它返回空白。
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.");
}
}
}
我希望代码输出输入的密码是否与主密码匹配,但是什么也不输出。
最佳答案
这是由于构造函数中的这一行而发生的:
enteredPassword = new String(masterPasswordField.getPassword());
刚创建时将使用该值,因此该值将为空白。
您应该在课程级别上使用
private JPasswordField masterPasswordField;
,然后在单击按钮时获取值:-public void actionPerformed(ActionEvent event)
{
if(new String(masterPasswordField.getPassword()).equals(masterPassword))
{
.
.
您可以摆脱
enteredPassword
变量。