JPasswordField KeyPress string length error?

你离开我真会死。 提交于 2019-11-29 14:00:20
trashgod

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.

Since JPasswordField extends from JTextComponent, you can attach a DocumentListener to it which is a far safer manner to update the background color on each change of the contents.

if (userPassword.length() >= 7)

This if statement doesn't match your comments:

//If password is 8+ characters

The actual code says if there are 7+ characters, then turn the background green. So when you are backspacing, it should turn the background red when you are down to 6 characters left.

I think your confusion is shown in this comment:

//(one less because string counting begins at 0)

What you are trying to describe is that indexing a character in a String starts at 0, for example when you use charAt() or subString(). This means that the first character is at index 0, the second at index 1, etc. On the other hand, length() returns the number of characters in the String. This is has nothing to do with the indexing, so you don't need to subtract 1.

I solved the problem by using KeyRelease instead of KeyPress, try it out my friend

Use

private void pstxtPasswordKeyReleased(java.awt.event.KeyEvent evt) 

Instead of

private void pstxtPasswordKeyPressed(java.awt.event.KeyEvent evt) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!