How to Create Login and Register Form in Java NetBeans with Text File
In this Java Long Tutorial we will go step by step on How To Design a Login And Register Form, plus how to use those two form with a text file so the user can signup and signin.   
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
- Text File.
What We Will Do In This Project:
- Design One Form For The Login and Signup Using JPanels and Borders.- Add an Icon Using JLabels To Close The Form.
- add Data into the text File When User Register.
- Allow The User to Login.
- Check If The User Leave Some Fields Empty.
- Check If The User Enter Username That Already Exists.
- Check If The User Enter a Wrong Password In The Confirmation Field.
- Check If The User Leave Some Fields Empty.
- Check If The User Enter Username That Already Exists.
- Check If The User Enter a Wrong Password In The Confirmation Field.
- Create a Message orm To Display When An Error Occure or To Display Any Information.
- Create a Main Form to Display After The User Login.
Project Source Code:
        // create a border for the jpanel
    Border panel_border = BorderFactory.createMatteBorder(2, 2, 2, 2, Color.gray);
    // create a border for the textfields
    Border textfields_border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.white);
    // optional red border
    Border textfields_red_border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.red);
    // create a border for the jlabels
    Border lbl_border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.lightGray);
    // the file path -> C:\Users\1BestCsharp\Desktop\java_app
    String usersFilePath = "C:\\Users\\1BestCsharp\\Desktop\\java_app\\users.txt";
    // array of all usernames
    ArrayList<String> all_usernames = new ArrayList<>();
    // a hashmap of usernames and password
    Map<String, String> usernameANDpassword = new HashMap<>();
    // the message frame
    Message_Frame msgF = new Message_Frame();
    public Login_And_Register() {
        initComponents();
        // image link: https://pixabay.com/vectors/cross-no-x-forbidden-closed-42928/
        // display close images in jlabel
        displayImage();
        // center the form
        this.setLocationRelativeTo(null);
        // set borders
        jPanel_main.setBorder(panel_border);
        jLabel_login_title.setBorder(lbl_border);
        jLabel_register_title.setBorder(lbl_border);
        jTextField_login_username.setBorder(textfields_border);
        jPasswordField_login_pass.setBorder(textfields_border);
        jTextField_register_username.setBorder(textfields_border);
        jTextField_register_fullname.setBorder(textfields_border);
        jTextField_register_email.setBorder(textfields_border);
        jPasswordField_register_pass.setBorder(textfields_border);
        jPasswordField_register_confirmPass.setBorder(textfields_border);
        getUsers();
        // test
        /*
        for(String uname:all_usernames)
        {
            System.out.println(uname);
        }
        */
    }
    // create a function to get all users
    public void getUsers()
    {
        // the info structure will be like this
        /*
        Username: aaa
        Fullname: bbb ccc
        Email: abc@mail.com
        Password: pass123
        ---
        */
        File file = new File(usersFilePath);
        String username = "";
        String password = "";
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            // read line by line from the text file
            Object[] lines = br.lines().toArray();
            for(int i = 0; i < lines.length; i++)
            {  
                // splite the row into two rows
                // one for the name of the field
                // and the other for the value of the field
                String[] row = lines[i].toString().split(": ");
                if(row[0].equals("Username"))
                {
                    // if it's the username field we will get the username
                    username = row[1];
                    // add the username to the all username array
                    all_usernames.add(username);
                }
                else if(row[0].equals("Password"))
                {
                    // if it's the password field we will get the password
                    password = row[1];
                }
                if(!username.equals("") && !password.equals(""))
                {
                    // add the username and the password to the hashmap
                    usernameANDpassword.put(username, password);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Login_And_Register.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // create a function to check if the username already exist
    public boolean checkIfUsernameExist(String un)
    {
        boolean exist = false;
        for(String username: all_usernames)
        {
            if(username.equals(un))
            {
                exist = true;
            }
        }
        return exist;
    }
    // function to display image
    public void displayImage()
    {
        ImageIcon imgico = new ImageIcon(getClass().getResource("\\/images/x.png"));
        Image img = imgico.getImage().getScaledInstance(jLabel_close_.getWidth(), jLabel_close_.getHeight(), Image.SCALE_SMOOTH);
        jLabel_close_.setIcon(new ImageIcon(img));
    }
    private void jLabel_close_MouseClicked(java.awt.event.MouseEvent evt) {                                           
        // close the form
        this.dispose();
    }                                          
    private void jButton_register_ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        // get the textfields data
        String username = jTextField_register_username.getText().trim();
        String fullname = jTextField_register_fullname.getText().trim();
        String email = jTextField_register_email.getText().trim();
        String password = String.valueOf(jPasswordField_register_pass.getPassword()).trim();
        String confirm_password = String.valueOf(jPasswordField_register_confirmPass.getPassword()).trim();
        File file = new File(usersFilePath);
        try {
            // file = the file we want to write on
            // true = we wan to append the text on it
            FileWriter fw = new FileWriter(file, true);
            // we need to check if the textfields are empty
            // we need to check if the confirmation password equal the password
            // we need to check if the username already exist
            // check if the textfields are empty
            if( username.equals("") || fullname.equals("") || email.equals("") || password.equals("") )
            {
                System.out.println("One Or More Fields Are Empty");
                msgF.jLabel_Title.setText("Signup Error");
                msgF.jLabel_message.setText("One Or More Fields Are Empty");
            }
            else{
                // confirmation password
                if(password.equals(confirm_password))
                {
                    // check if the username already exist
                    if(!checkIfUsernameExist(username))
                    {
                        fw.write("Username: " + username);
                        fw.write(System.getProperty("line.separator"));
                        fw.write("Fullname: " + fullname);
                        fw.write(System.getProperty("line.separator"));
                        fw.write("Email: " + email);
                        fw.write(System.getProperty("line.separator"));
                        fw.write("Password: " + password);
                        fw.write(System.getProperty("line.separator"));
                        fw.write("---");
                        fw.write(System.getProperty("line.separator"));
                        fw.close(); 
                        // populate the array and hashmap
                        getUsers();
                        msgF.jLabel_Title.setText("Signup");
                        msgF.jLabel_message.setText("You Have Created A New Account Successfully");
                    }
                    else
                    {
                       System.out.println("This Username Already Exist, Try Another One");  
                       msgF.jLabel_Title.setText("Signup Error");
                       msgF.jLabel_message.setText("This Username Already Exist, Try Another One");
                    }
                }
                else
                {
                    System.out.println("Password Confirmation Error");
                    msgF.jLabel_Title.setText("Signup Error");
                    msgF.jLabel_message.setText("The Confirmation Password Does Not Match");
                }
            }
            msgF.setVisible(true);
        } catch (IOException ex) {
            Logger.getLogger(Login_And_Register.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                                 
    private void jButton_login_ActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // get the username and password
        // the hashmap is unorderd
        String username = jTextField_login_username.getText().trim();
        String password = String.valueOf(jPasswordField_login_pass.getPassword()).trim();
        boolean userExist = false;
        // check if the fields are empty
        if(username.equals("") || password.equals(""))
        {
            msgF.jLabel_Title.setText("Login Error");
            msgF.jLabel_message.setText("You Need To Enter The Username And Password");
            msgF.setVisible(true);
            // you can change the jpanel color
            // you can use if to check which one is empty
            // or you can change the border
            /*
            if(username.equals("")){
                //jPanel_username.setBackground(Color.red);
                jTextField_login_username.setBorder(textfields_red_border);
            }
            else if(password.equals("")){
                //jPanel_password.setBackground(Color.red);
                jPasswordField_login_pass.setBorder(textfields_red_border);
            }
            */
        }
        else
        { 
           for(String uname: usernameANDpassword.keySet())
           {
               // check if the username exist
            if(uname.equals(username))
            {
                // check if the password is correct
                if(usernameANDpassword.get(uname).equals(password))
                {
                    userExist = true;
                   System.out.println("Welcome To The Appliction");
                   /*
                   msgF.jLabel_Title.setText("Login Successfully");
                   msgF.jLabel_message.setText("Welcome To The Appliction");
                   */
                   // show the main app form
                   App_Main_Frame mainF = new App_Main_Frame();
                   mainF.jLabel_welcome_.setText("Welcome Back " + uname);
                   mainF.setVisible(true);
                   // close the login form
                   this.dispose();
                   // break out from the for loop
                   break;
                }
            }
           }// outside the for loop
           if(userExist == false)
                {
                   msgF.jLabel_Title.setText("Login Error");
                   msgF.jLabel_message.setText("This User Doesn't Exist");
                   msgF.setVisible(true);
                }
        }
    }                                              
////// OUTPUT : 
More Java Projects:
Download Projects Source Code
    
  
  
  
