How to do it if the entered password or username is incorrect

How do I do this if the entered password or username is incorrect and only for 3 attempts?

public void keyPressed(KeyEvent e) {            
    if (e.getKeyChar() == KeyEvent.VK_ENTER) {

        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 {
            JOptionPane.showMessageDialog(null,"Incorrect Password or Username!!!",null,JOptionPane.WARNING_MESSAGE);               
        }           
    }   
}

      

+3


source to share


1 answer


Assuming it's just plain old Java (not Android or using a specific framework) you have a couple of options ...

You can create a flag outside of this method (but visible from the method) that tracks the number of user login attempts. Then when the KeyPressed action is called, your code should check if the user has reached the maximum attempts and do something.

Here's one idea for a global flag and a given maximum number of failed login attempts allowed.

public class MyClass {
    private int logInAttempts = 0;
    private final int MAX_LOGIN_ATTEMPTS = 3;

....
}

      

Then in your method it might look like this:



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);               
    }           
}   

      

}

Please note that if you are using this flag idea to track failed user login attempts, you need to increase it when the user fails to login as I did before "Invalid password or username" !!!! "

I hope this helps!

+4


source







All Articles