java 如何检查 JPassword 字段是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13460582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if JPassword field is null
提问by user1815823
I want to check the username and password in Swing.
我想在 Swing 中检查用户名和密码。
The check works for username, but it doesn't work for JPaswordfield. I am posting the related code:
该检查适用于用户名,但不适用于 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
回答by David Kroukamp
Very simple get the text using JPasswordField#getPassword()
which returns a char[]
of the text, then simply get the length of the array and check if it is equal to 0:
非常简单地使用JPasswordField#getPassword()
返回char[]
文本的文本获取文本,然后简单地获取数组的长度并检查它是否等于 0:
JPasswordField jpf...
if(jpf.getPassword().length == 0) {
// it is empty
}else {
// it is not empty
}