2012-11-19 137 views
0

我想在Swing中檢查用戶名和密碼。如何檢查JPassword字段是否爲

此檢查適用於用戶名,但不適用於JPaswordfield。我張貼了相關代碼:

//Here I get the password 
Char[] pwd = jt1.getPassword(); 
String s = new String(pwd); //converting char to string 
String p = s; 

//In the JButton checking username and password(Username check works fine but not passwordfield) 

jb.addActionListener(new ActionListener() { 
         public void actionPerformed(ActionEvent e) 
          { 
          if ((jt.getText().length()) == 0) 
          { 
            JFrame jf1 = new JFrame("UserName"); 
             jf1.setSize(401, 401); 
             //jf1.setVisible(true); 
             jf1.setDefaultCloseOperation(jf1.EXIT_ON_CLOSE); 
             JOptionPane.showMessageDialog(jf1, "User Name is empty"); 
          } 

         else if((p.length()) == 0) 
          { 

            JFrame jf1 = new JFrame("Password"); 
             jf1.setSize(401, 401); 
             //jf1.setVisible(true); 
             jf1.setDefaultCloseOperation(jf1.EXIT_ON_CLOSE); 
             JOptionPane.showMessageDialog(jf1, "Password is empty"); 
          } 

         else if ((p.length() == 0) && (jt.getText().length()) == 0) 
          { 
            JFrame jf1 = new JFrame("UserName and Password"); 
             jf1.setSize(401, 401); 
             //jf1.setVisible(true); 
             jf1.setDefaultCloseOperation(jf1.EXIT_ON_CLOSE); 
             JOptionPane.showMessageDialog(jf1, "Username and Password is 
empty"); 
          } 

          else 
          { //go to another method} 
Can someone help 

回答

6

很簡單的得到利用JPasswordField#getPassword()返回文本的char[],然後簡單地獲取數組的長度和檢查的文本,如果它等於0:

JPasswordField jpf... 

if(jpf.getPassword().length == 0) { 
    // it is empty 
}else { 
    // it is not empty 
} 
+0

謝謝大衛。有效。但爲什麼不是length()== 0,而是.length == 0? – user1815823

+1

@ user1815823因爲它是一個數組,其中有一個名爲'length'的變量,它給了我們數組中項目的長度/數量。雖然String沒有一個名爲'length'的變量,但它有一個名爲'length()'的方法,該方法計算了字符串長度希望,這有助於。也請點擊旁邊的勾號誰幫助你表示感謝 –

+1

感謝您的更正 – user1815823