我按照this Oracles tutorial讲述JPasswordField并创建了一个简单的演示应用程序:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;

public class JPasswordFieldDemo {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JPasswordField passwordField = new JPasswordField(20);
    JButton button = new JButton("Login");

    public JPasswordFieldDemo() {
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                char[] input = passwordField.getPassword();
                if (performCheck(input)) {
                    JOptionPane.showMessageDialog(null, "Correct password");
                } else {
                    JOptionPane.showMessageDialog(null, "Incorrect password");
                }
            }
        });
        passwordField.setEchoChar('*');
        panel.add(passwordField);
        panel.add(button);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private boolean performCheck(char[] input) {
        boolean isCorrect = false;
        char[] correctPass = { '1', '2', '3' };

        if (input.length != correctPass.length) {
            isCorrect = false;
        }
        if (Arrays.equals(input, correctPass)) {
            isCorrect = true;
        }
        Arrays.fill(correctPass, '0');

        return isCorrect;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JPasswordFieldDemo();
            }
        });
    }
}


现在,让我感到困惑的部分是在performCheck方法中。我的问题是:

有什么充分的理由为什么我应该比较两个字符数组的长度(就像他们在本教程中所做的那样)?

或者我的方法也可以像这样:

private boolean performCheck(char[] input) {
        boolean isCorrect = false;
        char[] correctPass = { '1', '2', '3' };

        if (Arrays.equals(input, correctPass)) {
            isCorrect = true;
        }
        Arrays.fill(correctPass, '0');

        return isCorrect;
    }


问候,并在此先感谢。

最佳答案

您的示例没有反映tutorial中显示的谓词,该谓词首先检查长度,然后仅在长度匹配时才检查内容。不等长的数组永远不能相等。

if (input.length != correctPassword.length) {
    isCorrect = false;
} else {
    isCorrect = Arrays.equals (input, correctPassword);
}

关于java - JPasswordField验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16510125/

10-10 17:06