JPasswordField KeyPress字符串长度错误?

jes*_*chk 6 java swing netbeans string-length jpasswordfield

我试图在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);
    }

}
Run Code Online (Sandbox Code Playgroud)

一切正常,除非我退格.键入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);
    }
Run Code Online (Sandbox Code Playgroud)

这段代码似乎对我有意义,但在测试中,颜色在第9个字符处变为绿色; 当退格时,它在6处变回红色.这似乎与我>= 7在第8个字符处颜色变为绿色但在5个字符处变为红色时的代码相同.

键入9个​​字符后,组件变为绿色

键入9个​​字符后,组件变为绿色

退回(从9开始)后,组件保持绿色,直到有6个字符

退回(从9开始)后,组件保持绿色,直到有6个字符

这很奇怪,因为我在此程序的按钮中有类似的代码,显示错误消息.该代码工作正常.这是一个KeyPress问题,可能与退格键有关吗?

tra*_*god 8

顺便说一下,检查返回的数组的长度getPassword(),而不是String从该数组构造的长度.这String是一种安全风险,因为它将使用易于找到的名称无限期地存储userPassword.

附录:这是罗宾建议使用的一个相关例子.我猜你的关键听众在处理它之前就已经看到了.DocumentListenerKeyEventJPasswordField

  • @Jaybob:这是Robin建议使用`DocumentListener`的相关[例子](http://stackoverflow.com/a/5342146/230513).我猜你的关键监听器在`JPasswordField`处理它之前看到了`KeyEvent`. (3认同)

Rob*_*bin 8

JPasswordField扩展开始JTextComponent,您可以附加一个DocumentListener,这是一种更安全的方式来更新内容的每次更改背景颜色.


Cod*_*ice 7

if (userPassword.length() >= 7)
Run Code Online (Sandbox Code Playgroud)

此if语句与您的注释不符:

//如果密码是8个以上的字符

实际代码表示如果有7个以上的字符,则将背景变为绿色.因此,当您退格时,当您剩下6个字符时,它应该将背景变为红色.

我认为你的困惑在这篇评论中有所体现:

//(one less because string counting begins at 0)
Run Code Online (Sandbox Code Playgroud)

你想要描述的是在一个开头的索引字符,例如当你使用或时.这意味着第一个字符位于索引处,第二个字符位于索引处等.另一方面,返回字符数.这与索引无关,因此您不需要减1.String0charAt()subString()01length()String