我正在为一个学校项目制作一个密码库,并且试图将“ 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.");
}
}
}
我希望代码输出输入的密码是否与主密码匹配,但是什么也不输出。
答案 0 :(得分:3)
这是由于构造函数中的这一行而发生的:-
enteredPassword = new String(masterPasswordField.getPassword());
您正在使用刚创建的值,因此该值将为空白。
您应该在课程级别接受private JPasswordField masterPasswordField;
,然后在单击按钮时获取值:-
public void actionPerformed(ActionEvent event)
{
if(new String(masterPasswordField.getPassword()).equals(masterPassword))
{
.
.
您可以摆脱enteredPassword
变量。
答案 1 :(得分:0)
您需要通过const obj = {};
titles.forEach((title, index) => {
obj[title] = values[index];
});
return obj;
方法调用getPassword()
。
actionPerformed()