Hello Friends, In this tutorial, we will learn How to Create Multi User Login Form in Java using MySQL Database step by step. You can implement this functionality in your Java Projects for improved security and robustness.
It will be a role-based login in Java in which the user will enter the username and password and his account type (Admin or User). Upon successful validation of the credentials, the user will be redirected to their respective dashboard.
Preview
Take a look at the preview of our Multi User Login form using Java, as it will provide you with a clearer understanding of the objective we aim to accomplish in this tutorial.
Prerequisite
Softwares
First, make sure you have downloaded and installed the following piece of software in your system.
Tutorials
To create our multi-user login form in Java, it is important to have a solid understanding of the following Java Swing components and Java Button click Event.
- JFrame Tutorial
- JLabel Tutorial
- JTextField Tutorial
- JButton Tutorial
- JPasswordField Tutorial
- JComboBox Tutorial
- Java JButton Click Event Tutorial
Once you have completed the topics mentioned above, we can now proceed with our tutorial on How to Create a Multi User Login form in Java using MySQL Database.
How to Create Multi User Login Form in Java using MySQL Database
#1 Setting up MySQL Database
- In this step, we will set up the MySQL Database. I am going to use MySQL Command Line Client for this purpose. If you don’t know how to correctly download and install MySQL Command Line Client in your system, then you can refer to my previous article How to install MySQL Commend Line Client.
- Once you have successfully downloaded and installed the MySQL Command Line Client on your system, proceed to open it.
- The MySQL Command Line Client will prompt you to enter your password, which should be the same password you provided during its installation. Simply input the password and press the enter button.
#2 Creating Database and Table in MySQL
- Now in this step, we will create the database (multiuserdb) in this example and inside that database, we will create a table (accoutnsinfo).
- Next, we will insert values and create two rows in our table, as given below.
1 2 3 4 5 |
create database multiuserdb; use multiuserdb; create table accountsinfo(ACCOUNT_TYPE varchar(30) not null,USERNAME varchar(30),PASSWORD varchar(30)); insert into accountsinfo values('Admin','Mahtab','1234'); insert into accountsinfo values('User','John','6789'); |
#3 Designing the Login Form
- In this step, we will design our Multi-User Login Form.
- To begin, ensure you import all the essential packages required for our program. This step will enable us to access the necessary interfaces and classes used throughout our code.
1 2 3 4 5 |
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; |
- Next, create a class MultiUserLoginForm. Inside this class, create the constructor of the class along with the main method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; public class MultiUserLoginForm { MultiUserLoginForm(){ } public static void main(String[] args) { } } |
- Next, create the object of the class MultiUserLoginForm, inside the main method.
1 |
MultiUserLoginForm multiUserLoginForm=new MultiUserLoginForm(); |
- Next, inside the class, MultiUserLoginForm, create the objects of all the swing components that we want to add in our Multi-User Login Form.
1 2 3 4 5 6 7 8 9 10 11 12 |
JFrame frame; JLabel loginIcon; JLabel title; JLabel userIcon; JLabel passwordIcon; JLabel selectAccountIcon; JTextField usernameTextField; JPasswordField passwordField; JButton loginButton; JButton closeButton; JComboBox comboBox; String[] values={"Select Account Type","Admin","User"}; |
- Next, inside the constructor of the class MultiUserLoginForm, we will set the properties of all the swing components that we have created.
- I have also added the icons to our Login Form, which I will provide you along with the source code. You have to add those icons inside the project folder.
- Code is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; public class MultiUserLoginForm { JFrame frame; JLabel loginIcon; JLabel title; JLabel userIcon; JLabel passwordIcon; JLabel selectAccountIcon; JTextField usernameTextField; JPasswordField passwordField; JButton loginButton; JButton closeButton; JComboBox comboBox; String[] values={"Select Account Type","Admin","User"}; MultiUserLoginForm(){ frame=new JFrame(); frame.setSize(350,500); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.getContentPane().setBackground(Color.white); frame.setResizable(false); ImageIcon icon1=new ImageIcon("login.png"); loginIcon =new JLabel(icon1); loginIcon.setBounds(115,20,icon1.getIconWidth(),icon1.getIconHeight()); title=new JLabel("Login"); title.setBounds(155,130,150,70); title.setFont(new Font("ARIAL",Font.BOLD,15)); comboBox=new JComboBox(values); comboBox.setBounds(110,195,180,30); comboBox.setBackground(Color.white); ImageIcon icon2=new ImageIcon("usertype.png"); selectAccountIcon =new JLabel(icon2); selectAccountIcon.setBounds(50,190,icon2.getIconWidth(),icon2.getIconHeight()); ImageIcon icon3=new ImageIcon("user.png"); userIcon =new JLabel(icon3); userIcon.setBounds(50,240,icon3.getIconWidth(),icon3.getIconHeight()); usernameTextField=new JTextField(); usernameTextField.setBounds(110,245,180,30); usernameTextField.setFont(new Font("ARIAL",Font.BOLD,15)); ImageIcon icon4=new ImageIcon("lock.png"); passwordIcon = new JLabel(icon4); passwordIcon.setBounds(50,295,icon4.getIconWidth(),icon4.getIconHeight()); passwordField=new JPasswordField(); passwordField.setBounds(110,300,180,30); passwordField.setFont(new Font("ARIAL",Font.BOLD,15)); loginButton=new JButton("Login"); loginButton.setBounds(65,360,100,30); loginButton.setFocusable(false); loginButton.setFont(new Font("Arial",Font.BOLD,15)); loginButton.setBackground(new Color(0,165,246)); loginButton.setForeground(Color.white); closeButton=new JButton("Close"); closeButton.setBounds(185,360,100,30); closeButton.setFocusable(false); closeButton.setFont(new Font("Arial",Font.BOLD,15)); closeButton.setBackground(new Color(244,67,54)); closeButton.setForeground(Color.white); frame.add(loginIcon); frame.add(title); frame.add(userIcon); frame.add(usernameTextField); frame.add(passwordIcon); frame.add(passwordField); frame.add(selectAccountIcon); frame.add(comboBox); frame.add(loginButton); frame.add(closeButton); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { MultiUserLoginForm multiUserLoginForm=new MultiUserLoginForm(); } } |
- Now run your program.
- As you can see that we have successfully designed our Login Form.
#4 Adding ActionListener to Buttons Using Anonymous Inner Class
- Next, inside the constructor of the class MultiUserLoginForm, we will implement the ActionListener to both of our buttons using the anonymous inner class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); |
#5 Adding MySQL Connector JAR file
- Now in this step, we will connect our program with the MySQL Database using JDBC (Java Database Connectivity).
- In order to establish a connection between your Java program and the MySQL database, you must include the MySQL JDBC driver, which comes in the form of a JAR file.
- The latest version of the MySQL Connector can be downloaded from the following link (MySQL Connector Java download).
- Upon visiting the link, opt for the “Platform Independent” option from the drop-down menu, as demonstrated in the figure below.
- Then download the Platform Independent (Architecture Independent), ZIP Archive as shown below.
- After extracting the zip archive, you will get the JAR file.
- After this, you need to include this JAR file in your program, which will enable the connection of your Java program with the MySQL database.
- For NetBeans users,
- Right click on the Libraries folder then select Add JAR/Folder and then you can add the JAR file to your project.
- For Eclipse users,
- Right click on the Project then select Properties —>>>>Java Build Path and then you can choose Add External JARs button to add the JAR file.
- For IntelliJ IDEA users,
- Go to File––>>>>Project Structure—>>>>Libraries then click on the “+” sign and select Java and then you can add the JAR file.
#6 Establishing Database Connection
With the JAR file already added, we are now prepared to establish the connection between our Java program and the MySQL Database.
We want that when someone clicks on the Login Button, then our program should be connected to the database. Therefore, we will code this inside the actionPerformed() method, which is related to the Login Button.
- Establish the connection using , DriverManager.getConnection(String URL), which returns a Connection reference.
- In the String URL parameter, You have to write in the following format: jdbc:mysql://localhost:3306/multiuserdb, “root”, “root” where:
- jdbc represents the API.
- mysql indicates the database.
- localhost denotes the server name where MySQL is running.
- 3306 represents the port number.
- multiuserdb is the name of the database. If your database has a different name, replace it accordingly.
- The first “root” stands for the MySQL database’s default username.
- The second “root” is the password provided during MySQL database installation.
- To handle potential SQL Exceptions during the connection process, ensure to enclose the code within a try-catch block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { //Establishing Connection Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/multiuserdb", "root", "root"); } catch (SQLException exception) { System.out.println("Error while connecting to the database"); } } }); |
#7 Validating User Credentials and Redirecting based on User Role
As we know, there are 3 fields in our Multi Login Form, Account_type, Username, and Password.
Now we want that,
- if any of the field is empty and the person clicks on the Login Button then a message dialog box should appear with the message “Please Enter all Fields“.
- When the Username and Password are incorrect, then the message should appear “Username & Password did not match“.
- If the Username & Password are correct and the right account type has been chosen, then the new window should open related to the user type. For this, we will create a new JFrame in a separate class.
- If the person clicks on the close button, then the program should exit.
- The whole program of our Multi User Login Form in Java is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
//Importing necessary packages import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; //Creating class public class MultiUserLoginForm { //Creating objects of the Swing Components JFrame frame; JLabel loginIcon; JLabel title; JLabel userIcon; JLabel passwordIcon; JLabel selectAccountIcon; JTextField usernameTextField; JPasswordField passwordField; JButton loginButton; JButton closeButton; JComboBox comboBox; //Creating values that we will add in the combobox String[] values={"Select Account Type","Admin","User"}; //Creating constructor of the class MultiUserLoginForm(){ //Setting properties of all the components frame=new JFrame(); frame.setSize(350,500); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.getContentPane().setBackground(Color.white); frame.setResizable(false); ImageIcon icon1=new ImageIcon("login.png"); loginIcon =new JLabel(icon1); loginIcon.setBounds(115,20,icon1.getIconWidth(),icon1.getIconHeight()); title=new JLabel("Login"); title.setBounds(155,130,150,70); title.setFont(new Font("ARIAL",Font.BOLD,15)); comboBox=new JComboBox(values); comboBox.setBounds(110,195,180,30); comboBox.setBackground(Color.white); ImageIcon icon2=new ImageIcon("usertype.png"); selectAccountIcon =new JLabel(icon2); selectAccountIcon.setBounds(50,190,icon2.getIconWidth(),icon2.getIconHeight()); ImageIcon icon3=new ImageIcon("user.png"); userIcon =new JLabel(icon3); userIcon.setBounds(50,240,icon3.getIconWidth(),icon3.getIconHeight()); usernameTextField=new JTextField(); usernameTextField.setBounds(110,245,180,30); usernameTextField.setFont(new Font("ARIAL",Font.BOLD,15)); ImageIcon icon4=new ImageIcon("lock.png"); passwordIcon = new JLabel(icon4); passwordIcon.setBounds(50,295,icon4.getIconWidth(),icon4.getIconHeight()); passwordField=new JPasswordField(); passwordField.setBounds(110,300,180,30); passwordField.setFont(new Font("ARIAL",Font.BOLD,15)); loginButton=new JButton("Login"); loginButton.setBounds(65,360,100,30); loginButton.setFocusable(false); loginButton.setFont(new Font("Arial",Font.BOLD,15)); loginButton.setBackground(new Color(0,165,246)); loginButton.setForeground(Color.white); closeButton=new JButton("Close"); closeButton.setBounds(185,360,100,30); closeButton.setFocusable(false); closeButton.setFont(new Font("Arial",Font.BOLD,15)); closeButton.setBackground(new Color(244,67,54)); closeButton.setForeground(Color.white); frame.add(loginIcon); frame.add(title); frame.add(userIcon); frame.add(usernameTextField); frame.add(passwordIcon); frame.add(passwordField); frame.add(selectAccountIcon); frame.add(comboBox); frame.add(loginButton); frame.add(closeButton); //Implementing ActionListener using Anonymous Inner class loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { //Getting values of the fields and storing them into String String accountType=comboBox.getSelectedItem().toString(); String userName=usernameTextField.getText(); String password=passwordField.getText(); //Establishing database connection Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/multiuserdb", "root", "root"); //Creating object of Prepared Statement PreparedStatement preparedStatement=connection.prepareStatement("select * from accountsinfo"); //Creating object of Result Set ResultSet resultSet=preparedStatement.executeQuery(); //Creating condition to check the Empty Field if(accountType.equalsIgnoreCase("Select Account Type")||userName.equalsIgnoreCase("")||password.equalsIgnoreCase("")){ JOptionPane.showMessageDialog(null,"Please Enter all Fields"); } else { //Looping the result set while (resultSet.next()) { if (accountType.equalsIgnoreCase(resultSet.getString("ACCOUNT_TYPE")) && userName.equalsIgnoreCase(resultSet.getString("USERNAME")) && password.equalsIgnoreCase(resultSet.getString("PASSWORD"))) { //Validating Admin Credentials if (accountType.equalsIgnoreCase("Admin")) { AdminWindow adminWindow = new AdminWindow();//Opening the Admin Window frame.dispose(); break; //Validating User Credentials } else if (accountType.equalsIgnoreCase("User")) { UserWindow userWindow = new UserWindow();//Opening the User Window frame.dispose(); break; } } } //Creating condition to check if the username & password did not match if(resultSet.isAfterLast()){ JOptionPane.showMessageDialog(null,"Username & Password did not match"); } } } catch (SQLException exception) { //If there is any error while connecting to database System.out.println("Error while connecting to the database"); } } }); //Actions to perform on clicking the Close Button closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ //Creating the object of Class MultiUserLoginForm multiUserLoginForm=new MultiUserLoginForm(); } } //Creating Admin window in separate class class AdminWindow extends JFrame{ AdminWindow(){ JFrame frame=new JFrame(); JLabel label=new JLabel("Admin Window"); frame.setSize(300,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); label.setBounds(100,100,100,50); frame.add(label); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } //Creating user window in separate class class UserWindow extends JFrame{ UserWindow(){ JFrame frame=new JFrame(); JLabel label=new JLabel("User Window"); frame.setSize(300,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); label.setBounds(100,100,100,50); frame.add(label); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } |
- Now run your program and enter the credentials.
Download Source Code
- You can download the source of the Multi User Login Form in Java Swing by clicking the link below.
So this was all from this tutorial about how to create multi user login form in Java using MySQL Database. If you have any questions or doubts regarding this post, feel free to let me know by commenting below.
Related Articles…
- Login Form in Java Swing with Source Code
- How to Connect MySQL Database in Java Using Eclipse
- How to Connect MySQL Database in Java Using NetBeans
- Tic Tac Toe Java Code against Computer
- Number Guessing Game in Java with Source Code
- Calculator Program in Java using Swing with Source Code
- How to Connect MS Access Database in Java