Hello friends. In this tutorial, we will learn how to create a Java Swing Login Form with Database Connection using MySQL Database. In the previous tutorial, we learned how to create a login form in Java Swing, but we had not connected that to the database. In this tutorial, we will connect our Java login page with the MySQL database, and then we will do the login authentication using the database.
In this Login application, we will also add a useful functionality, which is if the user forgets his password, then he can also reset the password.
So let’s start our tutorial about Java Swing Login Form with Database Connection using MySQL Database step by step. The source code of this tutorial is given at the end of the tutorial.
Java Swing Login Form with Database Connection using MySQL
Prerequisite
Before moving ahead to our tutorial, first of all, make sure that you have the following pieces of software in your system.
You’ll need the Java Development Kit installed on your system to compile and run Java code. You can download the latest version of the JDK from the official Oracle website.
To run the program as-is, you need a MySQL database server installed and running on your local machine.
You’ll need the MySQL JDBC driver to enable communication between your Java code and the MySQL database.
- Eclipse IDE or any Other Java IDE
While you can write and compile Java code using a simple text editor and command-line tools, using an IDE can greatly simplify development.
1. Setting up MySQL Database
- In this step, we will create the database and table using the MySQL Command Line Client or MySQL Workbench. For this tutorial, I am going to use MySQL Command Line Client.
- I assume you have already downloaded and installed the MySQL server in your system. If you haven’t, then you may prefer this tutorial – How to install MySQL server
Launch MySQL Command Line Client
- Next, Open the command prompt or terminal and launch the MySQL Command Line Client using the following command. And then, you have to enter the MySQL root password.
1 |
mysql -u root -p |
Create the Database
- Once you’re in the MySQL Command Line Client, you can create a new database using the follwing query. In our Java login system example, we’ll name the database “userlogindb” but you can choose a different name if you prefer.
1 |
CREATE DATABASE userlogindb; |
Use the Database
- After creating the database, switch to it using the following query.
1 |
USE userlogindb; |
Create the Table
- Now, in this step, we will create the table where the user login information will be stored. In our example, the table is named “userlogintable,” and it should have at least two columns: “USERNAME” and “PASSWORD” You can execute the following SQL query to create the table.
1 2 3 4 |
CREATE TABLE userlogintable ( USERNAME VARCHAR(255) PRIMARY KEY, PASSWORD VARCHAR(255) ); |
Insert Sample Data
- Now, we will populate our table with sample data. For this, we will use the INSERT INTO statement.
1 2 3 4 |
INSERT INTO userlogintable (USERNAME, PASSWORD) VALUES ('Mahtab', '1234'), ('Amit', '6789'), ('Rohit', '5473'); |
- So, we have created our database and table and will now move to the Java programming part.
2. Set Up Your Java Project
- Open your Java IDE (Eclipse, IntelliJ, NetBeans etc.).
- Create a new Java project named “LoginApp”.
If you don’t want to use any IDE, then you can simply start with any text editor like Notepad or Notepad++.
3. Create the Class “LoginFormDatabase”
- In this step, first of all, we will import all the required libraries for creating our login form, handling GUI components, and interacting with the MySQL database.
1 2 3 4 5 6 7 8 |
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; |
- Next, we will define our main class, LoginFormDatabase, and implement the ActionListener interface to handle GUI events such as button clicks.
1 |
public class LoginFormDatabase implements ActionListener { |
4. Create the Main Method
- In the LoginFormDatabase class, add a main method to start the application, and inside that, create an instance of the LoginFormDatabase class. This is the entry point of the application.
1 2 3 |
public static void main(String[] args) { LoginFormDatabase loginFormDatabase = new LoginFormDatabase(); } |
5. Creating GUI Components
- In this step, inside the “LoginFormDatabase” class, we will declare various components that will be part of the GUI, such as main window, labels, text fields, buttons, and a checkbox.
- By declaring these components at the class level, outside of any method, we ensure that they can be accessed and modified by different methods within the class.
1 2 3 4 5 6 7 8 9 |
JFrame frame=new JFrame("LOGIN FORM"); JLabel userLabel = new JLabel("USERNAME"); JLabel passwordLabel = new JLabel("PASSWORD"); JTextField userTextField = new JTextField(); JPasswordField passwordField = new JPasswordField(); JButton loginButton = new JButton("LOGIN"); JButton resetButton = new JButton("RESET"); JButton forgotPasswordButton=new JButton("FORGOT PASSWORD"); JCheckBox showPassword = new JCheckBox("Show Password"); |
6. Creating Constructor and Setting Up GUI
- In this step, we will create the constructor of our class “LoginFormDatabase”. The constructor is where we will set up the GUI by creating the main window of the application using the JFrame and then adding the GUI components (labels, text fields, buttons, and a checkbox) within the window.
- In this constructor, we will also set up event listeners to various components (buttons and a checkbox) using the addActionListener method.
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 |
LoginFormDatabase(){ frame.setSize(400,500); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); userLabel.setBounds(40,120,100,50); userLabel.setFont(new Font("Arial",Font.BOLD,17)); passwordLabel.setBounds(40,190,100,50); passwordLabel.setFont(new Font("Arial",Font.BOLD,17)); userTextField.setBounds(180,135,150,25); userTextField.setFont(new Font("Arial",Font.BOLD,15)); passwordField.setBounds(180,200,150,25); passwordField.setFont(new Font("Arial",Font.BOLD,15)); showPassword.setBounds(180,230,150,25); showPassword.setFont(new Font("Arial",Font.BOLD,15)); showPassword.setFocusable(false); loginButton.setBounds(40,280,130,35); loginButton.setFont(new Font("Arial",Font.BOLD,15)); loginButton.setFocusable(false); resetButton.setBounds(200,280,130,35); resetButton.setFont(new Font("Arial",Font.BOLD,15)); resetButton.setFocusable(false); forgotPasswordButton.setBounds(100,340,180,35); forgotPasswordButton.setFont(new Font("Arial",Font.BOLD,12)); forgotPasswordButton.setFocusable(false); frame.add(userLabel); frame.add(passwordLabel); frame.add(userTextField); frame.add(passwordField); frame.add(showPassword); frame.add(loginButton); frame.add(resetButton); frame.add(forgotPasswordButton); loginButton.addActionListener(this); resetButton.addActionListener(this); showPassword.addActionListener(this); forgotPasswordButton.addActionListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } |
7. Adding MySQL JDBC Driver JAR File
- 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. Then download the Platform Independent (Architecture Independent), ZIP Archive.
- 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.
8. Implementing Event Handling (actionPerformed Method)
- Now, in this step, we will implement the actionPerformed method to handle actions like login, reset, show password, and forgot password. The behavior we want in response after clicking any button or checkbox is coded inside the actionPerformed() method.
1 2 3 4 |
@Override public void actionPerformed(ActionEvent e) { // Handle login validation, show password, reset, and forgot password here. } |
Login Button Code/ Login Validation
When the Login Button is clicked, we want that,
- It should connect to the MySQL Database named “userlogindb” running on the local machine at port 3306 and use the username “root” and password “root” for authentication.
- Next, It should handle user authentication for the login form by retrieving user input.
- Next, it should query the database for the user records and validate them with the entered credentials by the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
if(e.getSource()==loginButton){ try{ String username =userTextField.getText(); String password=passwordField.getText(); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(username.equals("")||password.equals("")){ JOptionPane.showMessageDialog(null, "Please Enter all Fields"); }else{ while(resultSet.next()){ if(username.equalsIgnoreCase(resultSet.getString("USERNAME")) && password.equalsIgnoreCase(resultSet.getString("PASSWORD"))){ JOptionPane.showMessageDialog(null,"Login Successful"); break; } }if(resultSet.isAfterLast()){ JOptionPane.showMessageDialog(null,"Username or Password did not match"); } } }catch(Exception exception){ System.out.println("Error while connecting to the database"); } } |
- Any Exception might occur while connecting to the database, so the code is within the try-catch block.
Show Password Code
We want that when the Show Password checkbox is clicked,
- It should allow the users to toggle the visibility of the password they’ve entered in the password field.
1 2 3 4 5 6 7 |
if(e.getSource()==showPassword){ if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); } else { passwordField.setEchoChar('\u25CF'); } } |
Reset Button Code
We want that when the Reset Button is clicked,
- It should clear the input fields for both the username and password.
1 2 3 4 |
if(e.getSource()==resetButton){ userTextField.setText(""); passwordField.setText(""); } |
Forgot Password Button Code
We want that when the Forgot Password Button is clicked,
- It should close the Login Window and open the “Forgot Password” window for the Password Recovery.
- We will implement the logic of password recovery in a separate class, “ForgotPassword”.
1 2 3 4 |
if(e.getSource()==forgotPasswordButton){ frame.dispose(); ForgotPassword forgotPassword=new ForgotPassword(); } |
9. Creating Forgot Password Window for Password Recovery
In this class,
- we will create a Forgot Password Window with a text field for entering the username and buttons for changing the password or going back to the Login Form.
- If the correct username is entered and validated against the database and the change password button is clicked, we will move to the next window, where we can change the password.
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 |
class ForgotPassword implements ActionListener{ JFrame frame=new JFrame("FORGOT PASSWORD"); JLabel label=new JLabel("ENTER USERNAME"); JTextField textField=new JTextField(); JButton changePasswordButton=new JButton("CHANGE PASSWORD"); JButton backButton=new JButton("BACK"); ForgotPassword(){ frame.setSize(400,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); label.setBounds(120,70,500,20); label.setFont(new Font("Arial",Font.BOLD,15)); textField.setBounds(90,120,200,25); textField.setFont(new Font("Arial",Font.BOLD,16)); changePasswordButton.setBounds(75,170,140,25); changePasswordButton.setFocusable(false); changePasswordButton.setFont(new Font("Arial",Font.BOLD,10)); backButton.setBounds(240,170,70,25); backButton.setFocusable(false); backButton.setFont(new Font("Arial",Font.BOLD,10)); frame.add(label); frame.add(textField); frame.add(changePasswordButton); frame.add(backButton); changePasswordButton.addActionListener(this); backButton.addActionListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==changePasswordButton){ try{ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); System.out.println("Connected to the Database Successfully"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(textField.getText().equals("")){ JOptionPane.showMessageDialog(null,"Invalid Input"); } else{ while(resultSet.next()){ if(textField.getText().equalsIgnoreCase(resultSet.getString("USERNAME"))){ String username=textField.getText(); frame.dispose(); ChangePassword changePassword=new ChangePassword(username); break; } } if(resultSet.isAfterLast()){ JOptionPane.showMessageDialog(null,"Invalid Username"); } } }catch(Exception exception){ } } if(e.getSource()==backButton){ frame.dispose(); LoginFormDatabase loginFormDatabase=new LoginFormDatabase(); } } } |
10. Creating Change Password Window to Change Password
In this class,
- We’ll design a “Change Password” window that includes two password input fields for setting a new password and confirming it. The user will initiate the password change process by clicking the “Update” button, and the updated password will be saved in the database.
- If the user chooses to return to the login form, he can do so by clicking the “LOGIN” button.
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 |
class ChangePassword implements ActionListener{ String username; JFrame frame=new JFrame("CHANGE PASSWORD"); JLabel label1=new JLabel("TYPE NEW PASSWORD"); JLabel label2=new JLabel("RE-TYPE PASSWORD"); JPasswordField passwordField1=new JPasswordField(); JPasswordField passwordField2=new JPasswordField(); JButton submitButton=new JButton("UPDATE"); JButton loginButton=new JButton("LOGIN"); ChangePassword(String username){ this.username=username; frame.setSize(400,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); label1.setBounds(35,90,300,20); label1.setFont(new Font("Arial",Font.BOLD,13)); label2.setBounds(35,140,300,20); label2.setFont(new Font("Arial",Font.BOLD,13)); passwordField1.setBounds(190,90,180,20); passwordField1.setFont(new Font("Arial",Font.BOLD,13)); passwordField2.setBounds(190,140,180,20); passwordField2.setFont(new Font("Arial",Font.BOLD,13)); submitButton.setBounds(40,180,150,30 ); submitButton.setFont(new Font("Arial",Font.BOLD,13)); loginButton.setBounds(220,180,150,30 ); loginButton.setFont(new Font("Arial",Font.BOLD,13)); submitButton.addActionListener(this); loginButton.addActionListener(this); frame.add(label1); frame.add(label2); frame.add(passwordField1); frame.add(passwordField2); frame.add(submitButton); frame.add(loginButton); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==submitButton){ try{ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(passwordField1.getText().equals("")||passwordField2.getText().equals("")){ JOptionPane.showMessageDialog(null,"Please Enter both fields"); }else if(passwordField1.getText().equals(passwordField2.getText())){ while(resultSet.next()){ if(resultSet.getString("USERNAME").equalsIgnoreCase(username)){ preparedStatement=connection.prepareStatement("UPDATE userlogintable SET PASSWORD=? WHERE USERNAME=?"); preparedStatement.setString(1,passwordField1.getText()); preparedStatement.setString(2,username); preparedStatement.executeUpdate(); JOptionPane.showMessageDialog(null,"Password Updated Successfully"); } } }else{ JOptionPane.showMessageDialog(null,"Password did not Match"); } }catch(Exception exception){ } } if(e.getSource()==loginButton){ frame.dispose(); LoginFormDatabase loginFormDatabase=new LoginFormDatabase(); } } } |
11. Final Code
- The final code of our application, Java Swing Login Form with Database Connection using MySQL Database, is the following.
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class LoginFormDatabase implements ActionListener { JFrame frame=new JFrame("LOGIN FORM"); JLabel userLabel = new JLabel("USERNAME"); JLabel passwordLabel = new JLabel("PASSWORD"); JTextField userTextField = new JTextField(); JPasswordField passwordField = new JPasswordField(); JButton loginButton = new JButton("LOGIN"); JButton resetButton = new JButton("RESET"); JButton forgotPasswordButton=new JButton("FORGOT PASSWORD"); JCheckBox showPassword = new JCheckBox("Show Password"); LoginFormDatabase(){ frame.setSize(400,500); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); userLabel.setBounds(40,120,100,50); userLabel.setFont(new Font("Arial",Font.BOLD,17)); passwordLabel.setBounds(40,190,100,50); passwordLabel.setFont(new Font("Arial",Font.BOLD,17)); userTextField.setBounds(180,135,150,25); userTextField.setFont(new Font("Arial",Font.BOLD,15)); passwordField.setBounds(180,200,150,25); passwordField.setFont(new Font("Arial",Font.BOLD,15)); showPassword.setBounds(180,230,150,25); showPassword.setFont(new Font("Arial",Font.BOLD,15)); showPassword.setFocusable(false); loginButton.setBounds(40,280,130,35); loginButton.setFont(new Font("Arial",Font.BOLD,15)); loginButton.setFocusable(false); resetButton.setBounds(200,280,130,35); resetButton.setFont(new Font("Arial",Font.BOLD,15)); resetButton.setFocusable(false); forgotPasswordButton.setBounds(100,340,180,35); forgotPasswordButton.setFont(new Font("Arial",Font.BOLD,12)); forgotPasswordButton.setFocusable(false); frame.add(userLabel); frame.add(passwordLabel); frame.add(userTextField); frame.add(passwordField); frame.add(showPassword); frame.add(loginButton); frame.add(resetButton); frame.add(forgotPasswordButton); loginButton.addActionListener(this); resetButton.addActionListener(this); showPassword.addActionListener(this); forgotPasswordButton.addActionListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ LoginFormDatabase loginFormDatabase=new LoginFormDatabase(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==loginButton){ try{ String username =userTextField.getText(); String password=passwordField.getText(); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(username.equals("")||password.equals("")){ JOptionPane.showMessageDialog(null, "Please Enter all Fields"); }else{ while(resultSet.next()){ if(username.equalsIgnoreCase(resultSet.getString("USERNAME")) && password.equalsIgnoreCase(resultSet.getString("PASSWORD"))){ JOptionPane.showMessageDialog(null,"Login Successful"); break; } }if(resultSet.isAfterLast()){ JOptionPane.showMessageDialog(null,"Username or Password did not match"); } } }catch(Exception exception){ System.out.println("Error while connecting to the database"); } } if(e.getSource()==showPassword){ if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); } else { passwordField.setEchoChar('\u25CF'); } } if(e.getSource()==resetButton){ userTextField.setText(""); passwordField.setText(""); } if(e.getSource()==forgotPasswordButton){ frame.dispose(); ForgotPassword forgotPassword=new ForgotPassword(); } } } class ForgotPassword implements ActionListener{ JFrame frame=new JFrame("FORGOT PASSWORD"); JLabel label=new JLabel("ENTER USERNAME"); JTextField textField=new JTextField(); JButton changePasswordButton=new JButton("CHANGE PASSWORD"); JButton backButton=new JButton("BACK"); ForgotPassword(){ frame.setSize(400,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); label.setBounds(120,70,500,20); label.setFont(new Font("Arial",Font.BOLD,15)); textField.setBounds(90,120,200,25); textField.setFont(new Font("Arial",Font.BOLD,16)); changePasswordButton.setBounds(75,170,140,25); changePasswordButton.setFocusable(false); changePasswordButton.setFont(new Font("Arial",Font.BOLD,10)); backButton.setBounds(240,170,70,25); backButton.setFocusable(false); backButton.setFont(new Font("Arial",Font.BOLD,10)); frame.add(label); frame.add(textField); frame.add(changePasswordButton); frame.add(backButton); changePasswordButton.addActionListener(this); backButton.addActionListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==changePasswordButton){ try{ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(textField.getText().equals("")){ JOptionPane.showMessageDialog(null,"Invalid Input"); } else{ while(resultSet.next()){ if(textField.getText().equalsIgnoreCase(resultSet.getString("USERNAME"))){ String username=textField.getText(); frame.dispose(); ChangePassword changePassword=new ChangePassword(username); break; } } if(resultSet.isAfterLast()){ JOptionPane.showMessageDialog(null,"Invalid Username"); } } }catch(Exception exception){ } } if(e.getSource()==backButton){ frame.dispose(); LoginFormDatabase loginFormDatabase=new LoginFormDatabase(); } } } class ChangePassword implements ActionListener{ String username; JFrame frame=new JFrame("CHANGE PASSWORD"); JLabel label1=new JLabel("TYPE NEW PASSWORD"); JLabel label2=new JLabel("RE-TYPE PASSWORD"); JPasswordField passwordField1=new JPasswordField(); JPasswordField passwordField2=new JPasswordField(); JButton submitButton=new JButton("UPDATE"); JButton loginButton=new JButton("LOGIN"); ChangePassword(String username){ this.username=username; frame.setSize(400,300); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); frame.setResizable(false); label1.setBounds(35,90,300,20); label1.setFont(new Font("Arial",Font.BOLD,13)); label2.setBounds(35,140,300,20); label2.setFont(new Font("Arial",Font.BOLD,13)); passwordField1.setBounds(190,90,180,20); passwordField1.setFont(new Font("Arial",Font.BOLD,13)); passwordField2.setBounds(190,140,180,20); passwordField2.setFont(new Font("Arial",Font.BOLD,13)); submitButton.setBounds(40,180,150,30 ); submitButton.setFont(new Font("Arial",Font.BOLD,13)); loginButton.setBounds(220,180,150,30 ); loginButton.setFont(new Font("Arial",Font.BOLD,13)); submitButton.addActionListener(this); loginButton.addActionListener(this); frame.add(label1); frame.add(label2); frame.add(passwordField1); frame.add(passwordField2); frame.add(submitButton); frame.add(loginButton); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==submitButton){ try{ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogindb", "root", "root"); PreparedStatement preparedStatement=connection.prepareStatement("select * from userlogintable"); ResultSet resultSet=preparedStatement.executeQuery(); if(passwordField1.getText().equals("")||passwordField2.getText().equals("")){ JOptionPane.showMessageDialog(null,"Please Enter both fields"); }else if(passwordField1.getText().equals(passwordField2.getText())){ while(resultSet.next()){ if(resultSet.getString("USERNAME").equalsIgnoreCase(username)){ preparedStatement=connection.prepareStatement("UPDATE userlogintable SET PASSWORD=? WHERE USERNAME=?"); preparedStatement.setString(1,passwordField1.getText()); preparedStatement.setString(2,username); preparedStatement.executeUpdate(); JOptionPane.showMessageDialog(null,"Password Updated Successfully"); } } }else{ JOptionPane.showMessageDialog(null,"Password did not Match"); } }catch(Exception exception){ } } if(e.getSource()==loginButton){ frame.dispose(); LoginFormDatabase loginFormDatabase=new LoginFormDatabase(); } } } |
- Now, Let’s run our program.
- After running the program in the above image, you can see the GUI of our Login form in Java.
- Now, Enter the login credentials and click the Login Button to see what happens.
- As you can see in the above image, when we entered the right login credentials and then clicked on the Login button, then the message dialog box has been displayed with the message “Login Successful”.
- Now, we will enter the invalid username or password, tick the checkbox to reveal the password, and then click the “Login Button” to see what happens.
- In the image displayed above, you can observe that incorrect login credentials were input, and when the ‘show password’ checkbox was activated, the password became visible. Following the click on the Login button, a message dialog box appeared with the message “Username or Password did not Match”.
- Next, clicking on the Reset Button will reset the username text field and password field to blank.
- Next, we will click the Forgot Password button, which will redirect us to another window “Forgot Password”, where we need to enter the valid username to proceed with the password change process.
- Now, if we enter the valid username and click the Change Password button, it will redirect us to another window, “Change Password.”
- If we input the invalid username, it will give the message “Invalid Username.”
- If you want to Go Back to the Login Window again, you can do it by clicking on the “Go Back” Button.
- As you can see in the above image, when the password is entered and confirmed and then clicked on the Update Button, It gave the message “Password Updated Successfully.”
- If the Passwords do not match, the message box will give the message “Password did not Match.”
- You can also return to the Login window by clicking the “Login” Button.
Java Swing Login Form with Database Connection Source Code Download
- You can download the source code of this project by clicking on the link below.
So this was all from this tutorial about Java Swing Login Form with Database Connection 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
- Java Button Click Event
- How to Create Multi User Login Form in Java using MySQL Database
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Number Guessing Game in Java Swing with Source Code
- Menu Driven Program in Java Using Switch Case
- Calculator Program in Java Swing/JFrame with Source Code
- Registration Form in Java With Database Connectivity
- Tic Tac Toe Game in Java with Source Code
- Text to Speech in Java
- How to Create Splash Screen in Java
- Best Laptops for Java Programming
- How to Connecty MySQL Database in Java Using Eclipse
- How to Connect MySQL Database in Java using NetBeans
- How to Fetch Data from Database in Java to JTable
- Why Pointer are not used in Java