1、创建和初始化
passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);
如想改变密码框的占位符,调用setEchoChar
2、在ActionListener中获得密码
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (OK.equals(cmd)) { //Process the password.
char[] input = passwordField.getPassword();
if (isPasswordCorrect(input)) {
JOptionPane.showMessageDialog(controllingFrame,
"Success! You typed the right password.");
} else {
JOptionPane.showMessageDialog(controllingFrame,
"Invalid password. Try again.",
"Error Message",
JOptionPane.ERROR_MESSAGE);
}
//Zero out the possible password, for security.
Arrays.fill(input, '0');
passwordField.selectAll();
resetFocus();
} else ...//handle the Help button...
}
注意:不要说和getText方法获得密码串,而是使用getPassword,不仅出于安全因素考虑,而且getText可能返回类似“***”的无效字符串。
本文介绍如何在Java中创建安全的密码输入框,并通过监听器正确获取和验证密码,同时强调了安全操作的重要性。
2万+

被折叠的 条评论
为什么被折叠?



