2

我正在为一个学校项目制作密码保险库,我正在尝试将“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.");
        }
    }
}

我希望代码输出输入的密码是否与主密码匹配,但它不输出任何内容。

4

2 回答 2

3

这是因为构造函数中的这一行:-

enteredPassword = new String(masterPasswordField.getPassword());

您正在获取刚刚创建的值,因此该值将为空白。

您应该private JPasswordField masterPasswordField;在班级级别上,然后在单击按钮时获取值:-

public void actionPerformed(ActionEvent event)
{
    if(new String(masterPasswordField.getPassword()).equals(masterPassword))
    {
.
. 

你可以摆脱enteredPassword变量。

于 2019-01-16T01:09:12.850 回答
0

您需要调用方法getPassword()actionPerformed()

 public void actionPerformed(ActionEvent event)
    {
        enteredPassword = new String(masterPasswordField.getPassword());
        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.");
        }
    }
于 2019-01-16T01:19:59.113 回答