假设这只是常规的旧Java(而不是Android或使用特定的Framework),则您有几种选择…
您可以在此方法之外(但可以从该方法内部看到)创建一个标志,以跟踪用户登录失败的次数.然后,在调用keyPressed活动时,您的代码应检查用户是否已达到最大尝试次数,并相应地执行操作.
这是一个全局标志和设定的最大允许失败登录尝试次数的想法.
public class MyClass {
private int logInAttempts = 0;
private final int MAX_LOGIN_ATTEMPTS = 3;
....
}
然后在您的方法中,它看起来可能像这样:
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
if(logInAttempts == MAX_LOGIN_ATTEMPTS) {
// they've failed to login too many times
// lock them out, start a timer, or whatever
} else {
// go on to check if login is correct
if (userTf.getText().equals(dat.getUserName()) & passTf.getText().equals(dat.getPassWord())) {
JOptionPane.showMessageDialog(null,"Hello You are an Authorized User!!!",null,JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
} else {
// if using a flag for login attempts, you need to increment it
// when the user fails logging in
logInAttempts++;
JOptionPane.showMessageDialog(null,"Incorrect Password or Username!!!",null,JOptionPane.WARNING_MESSAGE);
}
}
}
请注意,如果您使用此标记提示来跟踪用户的失败登录尝试,则需要在用户登录失败时增加它,就像我在“错误的密码或用户名!!!”之前所做的那样.
希望对您有所帮助!