---
title: "Simple Registration Form using JAVA Swing"  
description: "MySQL is the world’s most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing"  
author: "Tarun Kumar"  
published: 2015-06-26  
updated: 2026-05-13  
canonical: https://www.mindstick.com/articles/1799/simple-registration-form-using-java-swing  
category: "java"  
tags: ["java", "mysql", "swing"]  
reading_time: 11 minutes  

---

# Simple Registration Form using JAVA Swing

## Simple Registration Form using JAVA Swing - Step2 (Connecting GUI with MySQL Database using JDBC)

Previously we have seen how to create a simple registration form in the swing

**:** [Simple Registration form](https://www.mindstick.com/articles/12557/login-and-registration-in-asp-dot-net-mvc) using Java Swing -

**Step-1**\

- ##### Introduction of MySQL: I think MySQL software is one of the most popular open-source relational SQL database management systems in the world. MySQL is one of the best RDBMS being used for developing web-based software applications. **The Database:** A database is a separate application that stores a collection of data. Every database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds. **RDBMS:** The Relational Database Management System (RDBMS) is a software that enables you to implement a database with tables, columns, and indexes. It is sure that the Referential Integrity between rows of various tables. it's almost all Updates the indexes automatically. If we describe a SQL query we find that An SQL query and combine information from various tables. ##### Definitions Related to Database: **In this Registration Form we will use some other packages, packages are:** **java.swing.table.DefaultTableModel**; DefaultTableModel returns a column class of Object. It is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. A code like **"java.sql.Connection"** : It is a connection (session) with a specific database. These SQL statements are executed and results are returned within the context of a connection. The Connection object's database is able to provide information describing its tables. **java.sql.PreparedStatement**:- The SQL statement is precompiled and stored in a PreparedStatement object. These objects can then be used to efficiently execute this statement multiple times. **java.sql.ResultSet:-** A data table representing a database result set, which is usually generated by executing a statement that queries the database. Here the ResultSet object maintains a cursor pointing to its current row of data. In the beginning, the cursor is positioned before the first row. And the next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be applied within a while loop to repeat through the result set. **java.sql.Statement:**- An object used for executing a static SQL statement and returning the results it produces. In a general way, The only one ResultSet object per Statement object can be open at the same time. So, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. Each execution methods in the Statement interface implicitly close a statement current ResultSet object if an open one exists. This is like - "**java.awt.event**":- These are provides interfaces and classes for dealing with different types of events fired by AWT components. This is like - **java.awt.Toolkit:**- These classes are the abstract superclass of all actual implementations of the Abstract Window Toolkit. Where the Subclasses of the Toolkit class, are used to bind the various components to particular native toolkit implementations. The code like **- java.awt.Dimension:**- A Dimension class encapsulates the width and height of a component (in integer precision) in a single object. A class is associated with certain properties of components. The several methods defined by the Component class and the LayoutManager interface return a Dimension object. If, the connecting java application with the MySQL database, we need to follow steps to perform database connectivity: (In these examples we are using MySQL as the database. Therefore, we need to know following information's for the MySQL database): The Driver class: A driver class for the MySQL database is com.mysql.jdbc.Driver. The Connection URL: A connection URL for the MySQL database is JDBC:MySQL://localhost:3306/project where JDBC is the API, MySQL is the database, localhost is the server name on which MySQL is running, you may also use an IP address, 3306 is the port number and project is the database name. You may use any database, in such case, you need to replace the project with your database name. **Username:** A default username for the MySQL database is root. **Password**: A Password is given by the user at the time of installing the MySQL database. In that example, we are going to use the root as the password. [ To connect java application with the MySQL database mysqlconnector.jar file is required to be loaded.]

   - A Database: The database is a collection of tables, with related data.

   - A Database Table: The table is a matrix with data. The table in a database looks like a simple spreadsheet.
   - The Table Columns: A column(of a Table) contain data of one and the same kind, for example, the column postcode.
   - The Table Row: A row (= tuple, entry or record) is a group of related data, for example, the data of one subscription.
   - Redundancy: The storing data twice, redundantly to make the system faster.
   - The Primary Key: A primary key is unique. A key-value can’t occur twice in one table. With the help of a key, we can find at most one row.
   - The Foreign Key: A foreign key is a linking pin between two tables.
   - The Compound Key: A compound key (composite key) is a key that consists of multiple columns because one column is not sufficiently unique.
   - The Index: An index in a database resembles an index at the back of a book.
   - The Referential Integrity: That is the Referential Integrity makes sure that a foreign key value

Java Codes:

##

##### RegistrationFormGUI.java

```
import java.awt.Color; import java.awt.Dimension;import java.awt.GridLayout;import java.awt.Toolkit;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.Statement;import javax.swing.BorderFactory;import javax.swing.ButtonGroup;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JRadioButton;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.JTextField;import javax.swing.table.DefaultTableModel;@SuppressWarnings("serial")public class RegistrationFormGUI extends JFrame{         Connection con;      Statement stmt;       PreparedStatement preStatement,updatePreStmt;      JLabel title, idLabel, nameLabel, genderLabel, addressLabel, contactLabel;      JTextField idField, nameField, genderField, addressField, contactField;      JButton registerButton, exitButton,updateButton,deleteButton,resetButton,              refresh;      JRadioButton male, female;      ButtonGroup bg;      JPanel panel;      JTable table;      DefaultTableModel model;      JScrollPane scrollpane;      public RegistrationFormGUI() {           // TODO Auto-generated constructor stub           super("REGISTRATION FORM");            setSize(770, 420);            setLayout(null);            // Calling connect method, this will connect us to database            connect();            // Defining Labels             title = new JLabel("Registration Form");            title.setBounds(60, 7, 200, 30);            idLabel = new JLabel("ID");            idLabel.setBounds(30, 50, 60, 30);            nameLabel = new JLabel("Name");             nameLabel.setBounds(30, 85, 60, 30);            genderLabel = new JLabel("Gender");             genderLabel.setBounds(30, 120, 60, 30);            addressLabel = new JLabel("Address");             addressLabel.setBounds(30, 155, 60, 30);             contactLabel = new JLabel("Contact");             contactLabel.setBounds(30, 190, 60, 30);            // Defining ID field            idField = new JTextField();             idField.setBounds(95, 50, 130, 30);            idField.setEnabled(false);            // Defining Name field            nameField = new JTextField();             nameField.setBounds(95, 85, 130, 30);                     // Defining Gender Buttons            male = new JRadioButton("Male");            male.setBounds(95, 120, 60, 30);            female = new JRadioButton("Female");            female.setBounds(155, 120, 70, 30);                        bg = new ButtonGroup();             bg.add(male);             bg.add(female);             addressField = new JTextField();             addressField.setBounds(95, 155, 130, 30);            contactField = new JTextField();             contactField.setBounds(95, 190, 130, 30);             // fixing all Label,TextField,RadioButton            add(title);            add(idLabel);            add(nameLabel);            add(genderLabel);            add(addressLabel);            add(contactLabel);            add(idField);            add(nameField);            add(male);            add(female);            add(addressField);            add(contactField);            // Defining Exit Button            exitButton = new JButton("Exit");             exitButton.setBounds(25, 250, 80, 25);                        // Defining Register Button            registerButton = new JButton("Register");            registerButton.setBounds(110, 250, 100, 25);            // Defining Update Button            updateButton = new JButton("Update");            updateButton.setBounds(110, 285, 100, 25);            updateButton.setEnabled(false);            // Defining Delete Button            deleteButton = new JButton("Delete");            deleteButton.setBounds(25, 285, 80, 25);            deleteButton.setEnabled(false);            // Defining Reset Button            resetButton = new JButton("Reset");            resetButton.setBounds(60, 320, 100, 25);            resetButton.setEnabled(false);             // fixing all Buttons            add(exitButton);            add(registerButton);            add(updateButton);            add(deleteButton);            add(resetButton);                // Defining Panel            panel = new JPanel();            panel.setLayout(new GridLayout());            panel.setBounds(250, 20, 480, 330);            panel.setBorder(BorderFactory.createDashedBorder(Color.blue));            add(panel);            // Defining Refresh Button            refresh = new JButton("Refresh Table");            refresh.setBounds(350, 350, 270, 15);            add(refresh);            //Defining Model for table            model = new DefaultTableModel();            //Adding object of DefaultTableModel into JTable            table = new JTable(model);            //Fixing Columns move            table.getTableHeader().setReorderingAllowed(false);            // Defining Column Names on model            model.addColumn("S.No");            model.addColumn("ID");            model.addColumn("Name");            model.addColumn("Gender");            model.addColumn("Address");            model.addColumn("Contact");             // Enable Scrolling on table           scrollpane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,                                           JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);            panel.add(scrollpane);            //Displaying Frame in Center of the Screen            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();            this.setLocation(dim.width/2-this.getSize().width/2,                             dim.height/2-this.getSize().height/2);            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            setResizable(false);            setVisible(true);      }      // Connection with Database      public void connect(){            try{                  Class.forName("com.mysql.jdbc.Driver");                  con =DriverManager.getConnection(                                  "jdbc:mysql://localhost:3306/test","root","1234");                  stmt = con.createStatement();                  preStatement = con.prepareStatement("insert into regForm(                                     name,gender,address,contact) values(?,?,?,?)");            }catch(Exception e){                  System.out.print(e.getMessage());            }      }}
```

DynamicRegForm Class – DynamicRegForm.java

```
import javax.swing.*;import javax.swing.table.DefaultTableModel; import java.awt.event.*;import java.sql.ResultSet;@SuppressWarnings("serial")public class DynamicRegForm extends RegistrationFormGUI{      String gender = "";      ResultSet rst,rstLast;      Object[][] data;      int serialNo;       String SHOW = "Show";      RegistrationFormGUI formGUIObject;      // Defining Constructor      DynamicRegForm(){            nameField.addKeyListener(new KeyAdapter() {                  public void keyTyped(KeyEvent e) {                  if(nameField.getText().length()>=15)                        e.consume();                  }            });            male.addActionListener(new ActionListener() {                  public void actionPerformed(ActionEvent e) {                        gender = "Male";                  }            });            female.addActionListener(new ActionListener() {                  public void actionPerformed(ActionEvent e) {                        gender = "Female";                  }            });            addressField.addKeyListener(new KeyAdapter() {                  public void keyTyped(KeyEvent e) {                  if(addressField.getText().length()>50)                        e.consume();                  }            });            contactField.addKeyListener(new KeyAdapter() {                  public void keyTyped(KeyEvent e) {                        char c = e.getKeyChar();                        if (!((c >= '0') && (c <= '9') ||                             (c == KeyEvent.VK_BACK_SPACE) ||                             (c == KeyEvent.VK_DELETE))) {                              // getToolkit().beep();                              e.consume();                        }                        if(contactField.getText().length()>9)                               e.consume();                  }            });            exitButton.addActionListener(new ActionListener(){                  public void actionPerformed(ActionEvent arg0) {                        try{                              con.close();                              System.exit(0);                        }catch(Exception ex){                               System.out.println(ex.getMessage());                        }                  }            });            registerButton.addActionListener(new AbstractAction(SHOW){                   public void actionPerformed(ActionEvent ae){                         try{                            if (ae.getSource() == registerButton) {                                if (nameField.getText().equals(""))                                   JOptionPane.showMessageDialog(idField,                                                "Please provide Name_Field");                                else if(addressField.getText().equals(""))                                   JOptionPane.showMessageDialog(idField,                                                "Please provide Address_Field");                                else if(contactField.getText().equals(""))                                   JOptionPane.showMessageDialog(idField, "Please provide Contact_Field");                                else if(gender.equals(""))                                   JOptionPane.showMessageDialog(idField, "Please select Gender");                                else {                                 //Fetching column values from Database                                 preStatement.setString(1,nameField.getText());                                 preStatement.setString(2,gender);                                 preStatement.setString(3,addressField.getText());                                 preStatement.setString(4,contactField.getText());                               //Executing MySQL Update Query                                 int i = preStatement.executeUpdate();                                 if(i==1){                                  JOptionPane.showMessageDialog(panel,                                                "Successfully Registered");                                 }                                  // showing last row                                 rstLast = stmt.executeQuery("select *from regForm");                                rstLast.last();                                String string = serialNo++ +",                                             "+String.valueOf(rstLast.getLong(1))+",                                             "+rstLast.getString(2)+",                                             "+rstLast.getString(3)+",                                             "+rstLast.getString(4)+",                                             "+rstLast.getString(5);                                 Object[] row = null;                                 row = string.split(",");                                 model.addRow(row);                                 panel.revalidate();                                  // fields are blank                                 blankFields();                               }                              }                       }catch(Exception ex){                              System.out.println(ex.getMessage());                        }                   }            });             updateButton.addActionListener(new AbstractAction(SHOW){              public void actionPerformed(ActionEvent e){                  if (nameField.getText().equals(""))                        JOptionPane.showMessageDialog(idField,                                    "Please provide Name_Field");                  else if(addressField.getText().equals(""))                        JOptionPane.showMessageDialog(idField,                                    "Please provide Address_Field");                  else if(contactField.getText().equals(""))                        JOptionPane.showMessageDialog(idField,                                    "Please provide Contact_Field");                                else if(gender.equals(""))                        JOptionPane.showMessageDialog(idField,                                    "Please select Gender");                                    else {                              int r = table.getSelectedRow();                              try{                              if(r>=0){                                 if(male.isSelected())                                    gender = male.getText();                                 else                                    gender = female.getText();                                    String id = (String)table.getModel().                                                              getValueAt(r,1);                                    updatePreStmt = con.prepareStatement(                                                    "update regForm set name=?,                                                    gender=?,address=?,contact=?                                                    where id="+id);                                  updatePreStmt.setString(1,nameField.getText());                                  updatePreStmt.setString(2,gender);                                  updatePreStmt.setString(3,addressField.getText());                                  updatePreStmt.setString(4,contactField.getText());                                  int i = updatePreStmt.executeUpdate();                                  if(i==1){                                     table.setValueAt(nameField.getText(),r,2);                                     table.setValueAt(gender, r, 3);                                     table.setValueAt(addressField.getText(),r,4);                                     table.setValueAt(contactField.getText(), r, 5);                                  }                                  else JOptionPane.showMessageDialog(panel,                                     "ID does't Exists in Database");                              }                              }catch(Exception ex){                                      System.out.println("Update section: "+                                                           ex.getMessage());                               }                        }              }          });             //Registering Anonymous Listener Class            deleteButton.addActionListener(new AbstractAction(SHOW){               public void actionPerformed(ActionEvent e){                  try{                   //Getting Selected Row No                  int r = table.getSelectedRow();                   if(r>=0){                         if (JOptionPane.showConfirmDialog(panel,                            "Are you sure want to Delete this 'RECORD' ?","WARNING",                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){                              String id = (String)table.getModel().getValueAt(r,1);                               // Executing MySQL Update Command                              int i = stmt.executeUpdate("delete from regForm                                                                  where id="+id);                              if(i==1){                                    model.removeRow(r);                                     // fields are blank                                    blankFields();                                    registerButton.setEnabled(true);                                    deleteButton.setEnabled(false);                                    updateButton.setEnabled(false);                              }                        }                  }                  }catch(Exception ex){                         System.out.println(ex.getMessage());                  }              }          });            //Registering Anonymous Listener Class            resetButton.addActionListener(new ActionListener(){                  public void actionPerformed(ActionEvent arg0) {                        // calling method resetFields()                        resetFields();                        registerButton.setEnabled(true);                        updateButton.setEnabled(false);                        deleteButton.setEnabled(false);                        resetButton.setEnabled(false);                  }            });            // Registering Anonymous Listener Class            refresh.addActionListener(new ActionListener() {                  public void actionPerformed(ActionEvent arg0) {                        //calling  refresh() method                        refreshTable();                  }            });            //Registering Anonymous Listener Class            table.addMouseListener(new MouseListener(){                  public void mouseClicked(MouseEvent arg0){                         //Getting Selected Row No                  int r = table.getSelectedRow();                  if(r>=0){                         deleteButton.setEnabled(true);                        updateButton.setEnabled(true);                        resetButton.setEnabled(true);                        registerButton.setEnabled(false);                         //Fetching records from Table on Fields                        idField.setText(""+table.getModel().getValueAt(r,1));                        nameField.setText(""+table.getModel().getValueAt(r,2));                        if(table.getModel().getValueAt(r,3).equals("Male"))                              male.setSelected(true);                        else                              female.setSelected(true);                        addressField.setText(""+table.getModel().getValueAt(r,4));                        contactField.setText(""+table.getModel().getValueAt(r,5));                  }                  }               //@Override                  public void mouseReleased(MouseEvent arg0) {}               //@Override                   public void mousePressed(MouseEvent arg0) {}                // @Override                   public void mouseExited(MouseEvent arg0) {}               //@Override                   public void mouseEntered(MouseEvent arg0) {}            });            // Displaying rows into the Frame table            addRows();      }      // addRows method      private void addRows(){            try{            Object[] row = null;            //Generating Serial No            serialNo=1;            rst = stmt.executeQuery("select *from regForm");            while(rst.next()){                   String string = serialNo++ +","+String.valueOf(rst.getLong(1))+",                                  "+rst.getString(2)+","+rst.getString(3)+",                                  "+rst.getString(4)+","+rst.getString(5);                  row = string.split(",");                  // Adding records in table model                   model.addRow(row);            }            panel.revalidate();            }catch(Exception ex){ System.out.println(ex.getMessage()); }      }      private void resetFields(){              //calling method blankfields()             blankFields();      }       // refresh method      private void refreshTable(){             // removing all the rows of the table            DefaultTableModel dm = (DefaultTableModel)table.getModel();            dm.getDataVector().removeAllElements();            System.out.println("Refresh Table");            //calling method addRows            addRows();      }      private void blankFields(){            // fields will be blank            idField.setText("");            nameField.setText("");            gender = "";            bg.clearSelection();            addressField.setText("");            contactField.setText("");      }      // main() method      public static void main(String[] args) {            new DynamicRegForm();      }     } 
```

##### Running the Application

![Simple Registration Form using JAVA Swing - Step2 (Connecting GUI  with MySQL Database using JDBC)](https://www.mindstick.com/mindstickarticle/53bdd5c8-6961-42ff-a4ac-0277ef05aeb2/images/8d9397e3-57be-464e-803c-727bc71ea0c1.png)

Next, we will learn about : Creating Dynamic Objective Test Application through Swing in JAVA ( Using MySQL Database )

---

Original Source: https://www.mindstick.com/articles/1799/simple-registration-form-using-java-swing

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
