2012-10-19 81 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)