JPasswordField KeyPress字符串长度错误? [英] JPasswordField KeyPress string length error?
问题描述
我正在尝试更改Java Swing(Netbeans)中JPasswordField的背景颜色.
这就是我所拥有的:
private void pstxtPasswordKeyPressed(java.awt.event.KeyEvent evt) {
//Get string from password box
userPassword = new String(pstxtPassword.getPassword());
//If password is 8+ characters
//(one less because string counting begins at 0)
if (userPassword.length() >= 7) {
//Set password input box background color to green
pstxtPassword.setBackground(Color.green);
}
else { //If password is less than 8 characters
//Set password input box background color to red
pstxtPassword.setBackground(Color.red);
}
}
一切正常,除非我退格.当我输入8个以上的字符后退格时,颜色不会变回红色,直到字段中只剩下5个字符为止.
我们将非常感谢您的帮助,我对Java编程和Netbeans还是陌生的.
我已经更改了代码,
//If password is 8+ characters
if ((pstxtPassword.getPassword()).length >= 8) {
//Set password input box background color to green
pstxtPassword.setBackground(Color.green);
}
else { //If password is less than 8 characters
//Set password input box background color to red
pstxtPassword.setBackground(Color.red);
}
这段代码对我来说似乎很有意义,但是在测试中,第9个字符的颜色变为绿色;当退格时,它在6时变回红色.这似乎是我在代码为>= 7
时遇到的相同问题,其中代码的第8个字符变为绿色,而第5个字符变为红色.
输入9个字符后,组件变为绿色
退格(从9开始)后,组件将保持绿色,直到有6个字符为止
这很奇怪,因为我在该程序的一个按钮中有类似的代码,该代码显示错误消息.该代码工作正常. 这是KeyPress问题吗,也许与退格键有关?
顺便说一句,检查getPassword()
返回的数组的长度,而不是从该数组构造的String
的长度. String
有安全隐患,因为它会以容易找到的名称userPassword
无限期存储.
附录:这是罗宾(Robin)的 解决方案
As an aside, examine the length of the array returned by getPassword()
, rather than the length of a String
constructed from that array. The String
is a security risk, as it will be stored for an indefinite time with the easily found name userPassword
.
Addendum: Here's a related example of Robin's suggestion to use DocumentListener
. I'm guessing that your key listener is seeing the KeyEvent
before the JPasswordField
has processed it.
这篇关于JPasswordField KeyPress字符串长度错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!