Search code examples
javaswingjcombobox

JComboBox and file read


I have login page that controle username and password.

I want that when admin is selected in combobox, then program should compare given username and password with first line in my "LoginInformation.txt" file.

And when user is selected in combobox and, then program should compare given username and pasword with second line in "LoginInformation.txt" file.

But,my code doesn't work correctly!

public class LoginFrame extends javax.swing.JFrame {

private String username;
private char[] Password;
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {

        username=String.valueOf(jTextField1.getText());
        Password=jPasswordField1.getPassword();

        if(jComboBox1.getSelectedIndex() == 0){
            if(adminCanGoNext()) {
              goAdminMainPage();
          }
           else{
                ErrorMessageLabel.setText("Did Not Match");
            }
        }


        else if(jComboBox1.getSelectedIndex() == 1){
            if(userCanGoNext()){
                goUserMainPage();
            }
        }



public boolean adminCanGoNext() throws IOException{
    FileReader fr=new FileReader("LoginInformation.txt");
    BufferedReader br=new BufferedReader(fr);
    String line;
    while((line=br.readLine()) != null){
        String[] infos=line.split("     ");
        String value=infos[0];
        String usern=infos[1];
        String pass=infos[2];

        if(usern.equals(username.trim()) && pass.equals(String.valueOf(Password))){
            return true;
        }
    }
    return false;
}

public void goAdminMainPage() {
          // Admin page
}


public boolean userCanGoNext() throws IOException{
    BufferedReader br=new BufferedReader(new FileReader("LoginInformation.txt"));
    String line;
    while( (line=br.readLine()) != null ){
        String[] celledinfo= line.split("     ");
        String userN=celledinfo[4];
        String passN=celledinfo[5];

        if(userN.equals(username.trim()) && passN.equals(String.valueOf(Password))){
            return true;
        }
    }
    return false;
}

public void goUserMainPage(){
          // User Page

}
}

my txt file:

Admin:     1     2
User:     1     3

i dont write generated codes by netbeans. (my first index in jcombobox is admin and second is user)

Thanks for help.


Solution

  • In adminCanGoNext you are checking the user/password against every line of your password file. You don't take care of the fact that the user selected "User" or "Admin". (and so that you only need to match against lines starting with "Admin:" or against lines starting with "User:")

    In userCanGoNext : there is a similar mistake, but additionally, you are looking for username and password at index 4 and 5. According the file template you have posted: the array resulting of the split will never have more than 3 elements.