我正在尝试更改 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 问题,也许与退格键有关?