2012-11-19 4 views
0

Swing에서 사용자 이름과 암호를 확인하고 싶습니다.JPassword 필드가 null인지 확인하는 방법

사용자 이름에 대한 확인이 작동하지만 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

아주 간단 0으로 동일한 경우는 단순히 배열의 길이를 얻을 수 및 확인 텍스트의 char[]을 반환 JPasswordField#getPassword()를 사용하여 텍스트를 얻을 :

JPasswordField jpf... 

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

데이비드에게 감사드립니다. 그것은 효과가 있었다. 하지만 왜 length() == 0이 아니라 .length == 0입니까? – user1815823

+1

@ user1815823 배열에있는 항목의 길이/수를 알려주는 'length'라는 변수가있는 Array이기 때문에. String에는'length'라는 변수가 없지만'length()'라는 메소드가 있습니다.이 메소드는 도움이되는 Strings 길이 희망을 계산합니다. 또한 감사의 표시에 도움을 주신 담당자의 답변 옆에있는 체크 표시를 클릭하십시오 –

+1

정정을 부탁드립니다 – user1815823

관련 문제