java - 如何检查 JPassword 字段是否为空

标签 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

最佳答案

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

JPasswordField jpf...

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

关于java - 如何检查 JPassword 字段是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13460582/

相关文章:

java - 获取 'Attempt to mutate notification' 异常

java - java中的sql变量查询

Java 面板对齐

java - JPasswordField.getPassword() 的安全原因是什么?

java密码字段: dot code

java - 使用 JPasswordField 及其 getText/getPassword 方法

java - 如果boolean在JVM中表示为int,那么它与Java的强类型是如何对应的呢?

java - HTTP 状态 400 - 客户端发送的请求在语法上不正确

java - 使用流将列表的集合与单个值结合起来

java - 标签移动时不调用paintComponent