我按照这个关于 JPasswordField 的 Oracles 教程创建了一个简单的演示应用程序:
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
方法。我的问题是:
有什么好的理由我应该比较两个 char 数组的长度(就像他们在教程中所做的那样)?
或者我的方法也可以是这样的:
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;
}
问候,并提前感谢。