Search code examples
javaoopnetbeanssysteminventory

How to create a login form - OOP in Java?


I already have a inventory system which accesses a certain table on a certain database.

Now I want to create a new frame that will serve as a login form before the user can proceed to the main inventory system frame.

I want it to access the same database but different table, (ex. user_table and item_table under the inventory_system_db database).

If the user logged on an admin account then he can access the inventory system with admin controls (ex. edit, add, delete).

And when he logged on as a normal user he will be able to access the inventory system but without admin controls.

Things I want to know:

  • How to create a login form?
  • How to make it proceed to inventory system?

Solution

  • If you want a Login Dialog just check the code below.

     public class LoginPane extends JDialog implements ActionListener {
      String itsUsername = "";
      String itsPassword = "";
      boolean itsFirst = true;
      boolean itsKeep = false;
      JTextField itsUserField = new JTextField(15);
      JPasswordField itsPassField = new JPasswordField(15);
      JCheckBox itsKeepBox = new JCheckBox("Save details:", false);
      boolean itsInit = false;
    
      public LoginPane() {
        super();
    setTitle("Login");
    setModal(true);
    getContentPane().setLayout(new GridLayout(3, 2));
    getContentPane().add(new JLabel("Username:"));
    getContentPane().add(itsUserField);
    getContentPane().add(new JLabel("Password"));
    getContentPane().add(itsPassField);
    getContentPane().add(itsKeepBox);
    JButton submit = new JButton("done");
    getContentPane().add(submit);
    submit.addActionListener(this);
    pack();
     }
    
    public String[] getLogin() {
    if (!itsKeep && !itsFirst) {
      return null;
    }
    if (!itsInit) {
      return null;
    }
    itsFirst = false;
    String[] res = new String[2];
    res[0] = itsUsername;
    res[1] = itsPassword;
    if (!itsKeep) {
      itsUsername = "";
      itsPassword = "";
    }
    return res;
      }
    
      public void actionPerformed(ActionEvent e) {
    itsUsername = itsUserField.getText();
    itsPassword = new String(itsPassField.getPassword());
    itsKeep = itsKeepBox.isSelected();
    itsInit = true;
    setVisible(false);
    }
    }
    

    You can add action for button as you wish!