我是JAVA GUI的新手,我刚刚开始学习,我开始编写此简单的身份验证框,而且我不确定为什么我的“ fogotpassword”按钮没有在“ else if(event.getSource() == forgotpassword)”中的方法。当我单击它时,什么也没有发生。其下的System.out.println(“ s”)无法打印。
非常感谢您的帮助:)。祝你有美好的一天。
public class miniProject extends JFrame
{
private JTextField UsernameBox;
private JPasswordField passwordField;
private JButton forgotpassword;
private JButton buttonLogin;
public miniProject()
{
super("Login Page");
setLayout(new GridLayout(3, 2,5,10));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
JLabel username = new JLabel(" Username:");
//username.setEditable(false);
add(username);
UsernameBox = new JTextField(10);
add(UsernameBox);
//item3.setEditable(false);
JLabel passowrd = new JLabel(" Password:");
add(passowrd);
passwordField = new JPasswordField(10);
add(passwordField);
buttonLogin = new JButton("Login");
add(buttonLogin);
forgotpassword = new JButton("Forgot My Password");
add(forgotpassword);
thehandler handler = new thehandler();
UsernameBox.addActionListener(handler);
passwordField.addActionListener(handler);
buttonLogin.addActionListener(handler);
forgotpassword.addActionListener(handler);
}
private class thehandler implements ActionListener
{
int i =5;
public void actionPerformed(ActionEvent event)
{
String string = "";
if (event.getSource()== passwordField || event.getSource()== UsernameBox ||event.getSource()==buttonLogin)
{
String password="";
if(passwordField.getPassword().length != 0 && UsernameBox.getText().length()!=0 )
{
for (char a :passwordField.getPassword())
{
password +=a;
}
password = password.trim();
if (password.equals("kyle") && UsernameBox.getText().equals("marcus"))
{
string = String.format("Welcome Back!", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
else
{
string = String.format("Incorrect Password\n "+i+" more attempts remaining until your account is locked", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
i--;
}
}
else if (event.getSource()==forgotpassword)
{
System.out.println("s");
String input = JOptionPane.showInputDialog("Enter your email");
if (input.length()!=0)
{
JOptionPane.showInternalMessageDialog(null, "Check your email to reset password!", "Password Reset",JOptionPane.PLAIN_MESSAGE);
}
}
else if (passwordField.getPassword().length == 0)
{
string = String.format("You didn't enter your password!",event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
else if (UsernameBox.getText().length()==0)
{
string = String.format("You didn't enter your username!",event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
}
}
}
该代码似乎没有按预期方式工作,因为if
方法第二行中的actionPerformed
不包含检查条件(如果忘记密码按钮是事件源)。您必须将此检查添加到外部if或将else if (event.getSource()==forgotpassword)
移到外部if之外。