我想在Java Swing(Netbeans)中更改JPasswordField的背景颜色。JPasswordField KeyPress字符串长度错误?
这是我有:
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个字符之后,直到有6个字符
这奇怪组件变绿
退格(从9开始)之后,部件保持绿色,因为我在这个程序的按钮中有类似的代码,它显示一个错误信息。该代码工作正常。 这是一个KeyPress问题,或许与退格键有关?
谢谢,我改变了它。 – jessechk
@Jaybob:这是一个相关的[示例](http://stackoverflow.com/a/5342146/230513)Robin's建议使用'DocumentListener'我猜你的关键监听器在'JPasswordField'处理之前看到'KeyEvent', – trashgod