在此Java Swing代码中验证用户名和密码时出现错误:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class LoginForm extends JFrame implements ActionListener {
private JButton login;
private JTextField name;
private JPasswordField pw;
private LoginForm() {
super("Log in");
login = new JButton("Log in");
name = new JTextField(20);
pw = new JPasswordField(20);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel fields = new JPanel(new BorderLayout());
fields.add(name, "North");
fields.add(new JScrollPane(), "Center");
fields.add(pw, "South");
add(fields, "Center");
add(new JPanel(), "South");
add(new JPanel(), "North");
JPanel j = new JPanel();
j.setSize(100, 400);
j.add(login);
//j.add(new JLabel("|\n|\n|-> Username"));
setSize(600, 400);
add(j, "West");
login.addActionListener(this);
setVisible(true);
}
public static void main(String[] args) {
new LoginForm();
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == login) {
if (!validUser(name.getText(), pw.getPassword())) JOptionPane.showMessageDialog(null, "This user not exists.\nFor create a user,\n edit 'database.lfrm' file."
, "Error!", JOptionPane.ERROR_MESSAGE);
else JOptionPane.showMessageDialog(null, "This user is valid! Congraulations!");
} else throw new RuntimeException("Event source isn't be a " + login.toString());
}
private static boolean validUser(String name, char[] pwd) {
boolean res = false;
try {
BufferedReader br = new BufferedReader(new FileReader("database.lfrm"));
String all = "", lines[], user[], line;
while ((line = br.readLine()) != null) all += line;
lines = all.split("\n");
user = Arrays.asList(lines).get(Arrays.asList(lines).indexOf(name + " $ " + new String(pwd))).split(" $ ");
if (user == new String[]{name, new String(pwd)}) res = true;
} catch (IOException e) {e.printStackTrace();}
return res;
}
}
我编译并运行了这段代码,但遇到了这个“错误”:
“
该用户不存在。
要创建用户,请编辑'database.lfrm'文件。
“
我的'database.lfrm'文件是这样的:
”
JavaUser $ adimn
”
我猜问题出在这里:
if (user == new String[]{name, new String(pwd)}) res = true;
执行此操作时,您正在检查“ user”和String []元素是否是同一对象,这是不正确的,因为String []元素是您为此验证而创建的另一个对象。
您要检查的是“用户”数组和下一个数组的内容是否相同,您可以通过以下方法替换此行:
if (Arrays.equals(user, new String[] {name, new String(pwd)})) res = true;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句