You are currently viewing Login Form in JavaFX with MySQL Database

Login Form in JavaFX with MySQL Database

JavaFX is used to create GUI, Desktop applications in Java. The problem with Java Swing is that it is outdated, people are started using JavaFX. So, it’s time to learn JavaFX.




Note: I will use Netbeans IDE throughout this article, you can use any other IDE’s you want.

Create a new project in Netbeans IDE
File-> New Project->JavaFX->JavaFX FXML Application-> Project Name-> Finish

Steps to be followed:

Step 1: Add MySQL JDBC Driver to your project

Step 2: Create two packages util and frames

Step 3: Inside util package, Create a java class with a name ‘ConnectionUtil’




Step 4: Inside frames package, Create two java class and two fxml files with name ‘FXMLDocument.fxml’, ‘FXMLMenu.fxml’, ‘FXMLDocumentController.java’ and ‘LoginApplication.java’

Step 5: Create DB a with name ‘swingapp’ and create a table with a name ’employee’

Open MySQL DB and execute this command,

CREATE DATABASE swingapp;

To create a table inside the newly created DB, execute this command,

USE swingapp;

Let’s create our table, by executing this query,

CREATE TABLE employee(
    id int not null primary key auto_increment,
    email varchar(55) not null,
    password varchar(55) not null
);

Now, insert some values into our table

INSERT INTO employee(email, password) VALUES('bushasn', '12345');
INSERT INTO employee(email, password) VALUES('bharath', '12345');

Here is the project structure for your reference

Now,  Let’s write our JDBC connection code,




ConnectionUtil.java

package com.codingbybushan.util;

import java.sql.*;
import javax.swing.*;
public class ConnectionUtil {
    Connection conn = null;
    public static Connection connectdb()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/swingapp","root","root");
            return conn;
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    }
}

Now, let’s write the main method, this class will extend the Application class

LoginApplication.java

package com.codingbybushan.frames;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author Bushan Sirgur
 */
public class LoginApplication extends Application {
    
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
    
}

Now, let’s design our login window, I created this login window using Scene builder, and here is the fxml version of that file,

FXMLDocument.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>


<AnchorPane id="AnchorPane" prefHeight="426.0" prefWidth="565.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.codingbybushan.frames.FXMLDocumentController">
   <children>
      <TextField fx:id="textEmail" layoutX="208.0" layoutY="90.0" />
      <PasswordField fx:id="textPassword" layoutX="208.0" layoutY="143.0" />
      <Label layoutX="115.0" layoutY="94.0" text="Email" />
      <Label layoutX="115.0" layoutY="147.0" text="Password" />
      <Button layoutX="208.0" layoutY="195.0" mnemonicParsing="false" onAction="#loginAction" text="Login" />
   </children>
</AnchorPane>

Once we logged into the application, another window will be open, and here is the fxml file for that,




FXMLMenu.fxml

<?xml version="1.0" encoding="UTF-8"?>
 
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
 
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1">
 
</AnchorPane>

Now, let’s write the controller part, here will get the connection, and we will query to the DB, if the email and password exists then we will allow the user, otherwise, we will display an alert message,

FXMLDocumentController.java

package com.codingbybushan.frames;

import com.codingbybushan.util.ConnectionUtil;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

/**
 *
 * @author Bushan Sirgur
 */
public class FXMLDocumentController implements Initializable {
    
    @FXML
    private TextField textEmail;
    
    @FXML
    private PasswordField textPassword;
    
    Stage dialogStage = new Stage();
    Scene scene;
    
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    public FXMLDocumentController() {
        connection = ConnectionUtil.connectdb();
    }
    
    
    
    public void loginAction(ActionEvent event){
        String email = textEmail.getText().toString();
        String password = textPassword.getText().toString();
    
        String sql = "SELECT * FROM employee WHERE email = ? and password = ?";
        
        try{
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, email);
            preparedStatement.setString(2, password);
            resultSet = preparedStatement.executeQuery();
            if(!resultSet.next()){
                infoBox("Please enter correct Email and Password", null, "Failed");
            }else{
                infoBox("Login Successfull",null,"Success" );
                Node node = (Node)event.getSource();
                dialogStage = (Stage) node.getScene().getWindow();
                dialogStage.close();
                scene = new Scene(FXMLLoader.load(getClass().getResource("FXMLMenu.fxml")));
                dialogStage.setScene(scene);
                dialogStage.show();
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    
    public static void infoBox(String infoMessage, String headerText, String title){
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setContentText(infoMessage);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.showAndWait();
    }
    
    
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        
    }    
    
}

Now, clean the project and run, you will see this window,

Enter wrong email and password, you will get this alert window,




Now enter the correct email and password, it will allow you to enter the application,

Once you click the ok, the current window/login window will get close and new window will open,

That’s it for this article, do let me know about this article, you can reach me on all my social media profiles, if you like this content, share with your friends.
Thanks for reading, I will see you in the next article.




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has 5 Comments

  1. Raj

    Hi
    Thank you for a very informed tutorial.
    Would you be able to amend this so that the username is passed to the next scene and also to have only one scene active at any time?
    Regards
    Raj

    1. Bushan Sirgur

      Thaks for reaching out. Yes we can do that. I will try to make a video/post on it.

  2. moussa

    Thank you man all working but i have problem with registration form can you do atuto like this?

Leave a Reply to moussa Cancel reply