如何检查JPassword字段是否为空

use*_*823 2 java swing jpasswordfield

我想检查Swing中的用户名和密码.

该检查适用于用户名,但它不适用于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
Run Code Online (Sandbox Code Playgroud)

Dav*_*amp 9

非常简单的获取文本使用JPasswordField#getPassword()返回char[]文本的一个,然后只需获取数组的长度,并检查它是否等于0:

JPasswordField jpf...

if(jpf.getPassword().length == 0) {
    // it is empty
}else {
   // it is not empty
}
Run Code Online (Sandbox Code Playgroud)

  • @ user1815823因为它是一个数组,所以有一个名为`length`的变量,该变量为我们提供了数组中项目的长度/数量。尽管String没有一个叫做length的变量,但是它有一个叫做length()的方法,该方法计算希望的String长度。也请点击帮助您表示感谢的人答案旁边的勾号 (2认同)