您好我正在用Java编写一个简单的登录程序,即使输入了正确的帐号和密码,我也遇到了问题我还是得到了“请输入正确的帐号/密码”,我似乎无法看到错误是
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main2 extends JFrame{
public static int x=0;
public JPanel panel;
String accountnumber = "123456";
JTextField inputUser;
String password = "admin";
JPasswordField inputPass;
public JLabel lblctr;
public Main2(){
setTitle("Login");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(500, 450, 500, 500);
panel = new JPanel();
setContentPane(panel);
panel.setLayout(null);
inputUser = new JTextField();
inputUser.setBounds(130, 30,125, 20);
panel.add(inputUser);
inputUser.setColumns(10);
inputPass = new JPasswordField();
inputPass.setBounds(130, 60, 125, 20);
panel.add(inputPass);
inputPass.setColumns(10);
lblctr = new JLabel("Attempts:");
lblctr.setBounds(80, 135, 72, 17);
panel.add(lblctr);
JButton cancelbtn = new JButton("Cancel");
cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
JButton loginbtn = new JButton("Login");
loginbtn.addActionListener(new ActionListener(){
@SuppressWarnings("deprecation") public void actionPerformed(ActionEvent arg0){
if((inputUser.getText().equals(accountnumber)) && (inputPass.getPassword().equals(password))){
JOptionPane.showMessageDialog(null,"Press OK to Continue!","Login success!",JOptionPane.INFORMATION_MESSAGE);
}
else{
x++;
if(x>3){
JOptionPane.showMessageDialog(null,"Too many attempts","Access Denied!",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
else{
JOptionPane.showMessageDialog(null,"Please input correct Account Number/Password","Login Failed!",JOptionPane.ERROR_MESSAGE);
}
}
lblctr.setText("Attempts : "+x);
}});
cancelbtn.setBounds(170,105, 89, 21);
panel.add(cancelbtn);
loginbtn.setBounds(50,105, 89, 21);
panel.add(loginbtn);
JLabel lbluser = new JLabel("Account Number:");
lbluser.setBounds(12, 34, 100, 10);
panel.add(lbluser);
JLabel lblpass = new JLabel("Password:");
lblpass.setBounds(50, 62, 72, 17);
panel.add(lblpass);
}
public static void main (String[]args){
Main2 proj = new Main2();
proj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
proj.setVisible(true);
proj.setSize(320,190);
proj.setLocationRelativeTo(null);
}
}
答案 0 :(得分:3)
JPasswordField#getPassword()
返回一个char数组,而不是String,因此比较" password"和inputPass.getPassword()直接绑定失败。使用Arrays方法比较char数组,而不是equals(...)
方法。
此外,user7是正确的,您尝试将密码变量名称用作String也将失败。摆脱报价。
如,
if (Arrays.equals(password.toCharArray(), inputPass.getPassword()))
其他问题:
@SuppressWarnings("deprecation")
。该代码已被弃用,原因很充分,不应使用。而是转到API以查看代码被弃用的原因并使用API建议的替代方案。setBounds(...)
,因为这会使非常不灵活的GUI,虽然它们在一个平台上看起来很好但在大多数其他平台或屏幕分辨率上看起来很糟糕而且非常困难更新和维护。而是使用布局管理器来帮助您创建外观漂亮,功能强大且易于维护的GUI。