【问题标题】:How to check if JPassword field is null如何检查密码字段是否为空
【发布时间】:2012-11-19 19:18:40
【问题描述】:

我想在 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

【问题讨论】:

    标签: java swing jpasswordfield


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢大卫。有效。但为什么不是 length() == 0 而是 .length ==0?
    • @user1815823 因为它是一个数组,它有一个名为length 的变量,它为我们提供了数组中项目的长度/数量。虽然 String 没有名为 length 的变量,但它有一个名为 length() 的方法,用于计算字符串长度,希望对您有所帮助。也请单击帮助您表示感谢的人的答案旁边的勾号
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多