I am trying to change the background colors of JPasswordField in Java Swing (Netbeans).
Here is what I have:
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); } }
Everything works, except when I fell behind. When I return after entering 8 + characters, the color will not change to red until there are only 5 characters left in the field.
Help will be appreciated, I am very new to programming in Java and Netbeans.
EDIT: I changed my code,
//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); }
This code seems to make sense to me, but when testing, the color changes to green at the 9th character; when moving backwards, it changes to red by 6. This seems to be the same problem as mine when the code was >= 7 , where the color changed green to the eighth character but changed to red with 5 characters.

After entering 9 characters, the component will turn green

After returning (starting from 9), the component remains green until there are 6 characters
This is strange because I have a similar code in a button in this program that displays an error message. This code is working fine. Is this a KeyPress problem, maybe something is related to the backspace key?
source share