2012-10-19 82 views
6

我想在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个字符处变回红色。

After typing 9 characters, the component turns green

键入9个字符之后,直到有6个字符

这奇怪组件变绿

After backspacing (starting from 9), component remains green until there are 6 characters

退格(从9开始)之后,部件保持绿色,因为我在这个程序的按钮中有类似的代码,它显示一个错误信息。该代码工作正常。 这是一个KeyPress问题,或许与退格键有关?

回答

8

另外,检查由getPassword()返回的数组的长度,而不是从该数组构造的String的长度。 String存在安全风险,因为它将以易于找到的名称userPassword无限期存储。

附录:这是一个相关的example Robin的suggestion使用DocumentListener。我猜测你的关键听众在JPasswordField处理它之前看到了KeyEvent

+0

谢谢,我改变了它。 – jessechk

+3

@Jaybob:这是一个相关的[示例](http://stackoverflow.com/a/5342146/230513)Robin's建议使用'DocumentListener'我猜你的关键监听器在'JPasswordField'处理之前看到'KeyEvent', – trashgod

7
if (userPassword.length() >= 7) 

这个if语句不符合您的评论:

//如果密码是8 +字符

实际的代码表示,如果有7+字符,然后打开背景绿色。因此,当您退格时,应该将背景变为红色,当您还剩下6个字符时。

我觉得你的困惑在此评论显示:

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

你所试图描述的是索引0String开始的字符,例如当您使用charAt()subString()。这意味着第一个字符位于索引0,索引1处的第二个字符等。另一方面,length()返回String中的字符数。这与索引无关,因此您不需要减1。

+0

OK,所以'长度()'返回字符串中的字符数。 我最初有'if(userPassword.length()> = 8',但经过测试,当我输入8个字符时,背景仍然是红色,当我输入第9个字符时,背景会变成绿色。它到'> = 7',它出于某种原因工作。我仍然不知道为什么它保持绿色,直到我退格到5个字符。谢谢你的帮助,但 – jessechk

+0

@Jaybob要调试此代码,我会开始打印为了确保它是你所期望的,请输出'userPassword'的值。 –

8

由于JPasswordFieldJTextComponent延伸,您可以附加DocumentListener它更安全的方式更新内容的每个更改背景颜色。

+1

对于'DocumentListener' +1。 – trashgod

0

我用,而不是按键响应KeyRelease解决了这个问题,尝试一下我的朋友

0

使用

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

代替

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