Java Bus Reservation System – Smarter, Faster, Better

FREE Online Courses: Click for Success, Learn for Free - Start Now!

In this project, we will be creating a Bus Reservation System using the Java swing library and Sqlite database. This system will have two separate modules, Admin and User the admin can delete the reservations, user and buses and can add new buses into the system while the customer can add their reservation and check their Reservation details. The customer module will also have the option to register new customers.

About Java Bus Reservation System

By the end of this project, you will be able to create a fully functional Bus Reservation System using Java Swing library, which includes two modules – Admin and User. You will learn how to implement various features in both modules, such as adding and deleting reservations, buses, and users.

Additionally, you will also learn how to allow customers to add their reservations, check their details, and register new customers. This project will provide you with a comprehensive understanding of the Java Swing library and sqlite database and equip you with the skills necessary to create a robust and efficient Bus Reservation System.

Prerequisite for Bus Reservation System using Java

Before starting this Java project, you should have the following:

  • Basic knowledge of Java programming language and its concepts
  • Eclipse IDE is installed on your system. You can download Eclipse from their official website and install it.
  • Familiarity with the Java Swing library, which is used to create the graphical user interface (GUI) of the Bus Reservation System.
  • Knowledge of SQLite, which is the database management system used in this project. You can download the SQLite JDBC driver and add it to your project.
  • Basic understanding of SQL, which is the language used to manage and manipulate the SQLite database.

Download Java Bus Reservation System Project

Please download the source code of Java Bus Reservation System Project: Java Bus Reservation System Project Code

Steps to Create Bus Reservation System Project using Java

Following are the steps for developing the Java Bus Reservation System Project:

Step 1: Create a new project in Eclipse.
Step 2: Create the required classes.

Step 1: Create a new project in Eclipse:

For this, you can head on to Eclipse and click on File>New>Java Project. Then give an appropriate name to the project such as “Bus Reservation System”

Step 2: Create the required classes:

For this, you can Right click on the project folder and select New>Java Class and then you can name the class accordingly.

Create the following classes:

WelcomeWindow: This class will be the welcome screen of our application and it will provide two login options the Admin and the User

Here’s the code for this class:

package org.ProjectGurukul;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import java.awt.Color;

public class WelcomeWindow {

    private JFrame frmBusReservationSystem;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    WelcomeWindow window = new WelcomeWindow();
                    window.frmBusReservationSystem.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public WelcomeWindow() {
        DatabaseOperations.dbInit();
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmBusReservationSystem = new JFrame();
        frmBusReservationSystem.getContentPane().setBackground(new Color(54, 70, 82));
        frmBusReservationSystem.setTitle("Bus Reservation System By ProjectGurukul");
        frmBusReservationSystem.setBounds(100, 100, 440, 202);
        frmBusReservationSystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmBusReservationSystem.getContentPane().setLayout(null);
        
        JLabel lblWelcome = new JLabel("Welcome to Bus Reservation System");
        lblWelcome.setForeground(new Color(255, 255, 255));
        lblWelcome.setBounds(0, 0, 440, 35);
        lblWelcome.setFont(new Font("Jua", Font.BOLD, 20));
        lblWelcome.setHorizontalAlignment(SwingConstants.CENTER);
        frmBusReservationSystem.getContentPane().add(lblWelcome);
        
        JLabel lblInstruction = new JLabel("Please Select Login profile:");
        lblInstruction.setForeground(new Color(255, 255, 255));
        lblInstruction.setBounds(113, 12, 218, 52);
        frmBusReservationSystem.getContentPane().add(lblInstruction);
        
        JButton btnAdmin = new JButton("Admin");
        btnAdmin.setBounds(161, 50, 117, 50);
        btnAdmin.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                frmBusReservationSystem.dispose();
                AdminLogin adminLogin= new AdminLogin();
            }
            
        });
        frmBusReservationSystem.getContentPane().add(btnAdmin);
        
        JButton btnUser = new JButton("User");
        btnUser.setBounds(161, 105, 117, 50);
        btnUser.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                frmBusReservationSystem.dispose();
                UserLogin userLogin = new UserLogin();
                
                
            }
        });
        frmBusReservationSystem.getContentPane().add(btnUser);
    }
}

AdminLogin: This class provides the admin login screen to our application

Code:

package org.ProjectGurukul;

import java.awt.EventQueue;
import java.awt.Frame;

import javax.swing.JFrame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

public class AdminLogin  {

    private JFrame frame;
    private JTextField adminNameField;
    private JPasswordField passwordField;
    private final String  adminName = "Admin";
    private final String password = "1234";

    public AdminLogin() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setTitle("Admin Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        JLabel lblAdmin = new JLabel("Admin Name");
        lblAdmin.setBounds(0, 67, 173, 36);
        frame.getContentPane().add(lblAdmin);
        
        adminNameField = new JTextField();
        adminNameField.setBounds(222, 68, 184, 36);
        frame.getContentPane().add(adminNameField);
        adminNameField.setColumns(10);
        
        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(0, 134, 173, 36);
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        passwordField.setBounds(220, 135, 184, 36);
        frame.getContentPane().add(passwordField);
        
        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(161, 201, 117, 25);
        btnLogin.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                if(adminNameField.getText().equals(adminName) && password.equals(new String(passwordField.getPassword()))) {					frame.dispose();
                    AdminPanel ap = new  AdminPanel(); 
                    
                }else {
                    JOptionPane.showMessageDialog(btnLogin, "Incorrect Username or Password");;
                }
                
            }
        });
        frame.getContentPane().add(btnLogin);
        frame.setVisible(true);
    }
}

UserLogin: This class provides the user login and register window

Code:

package org.ProjectGurukul;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;

public class UserLogin {
    private JFrame frame;
    private JTextField idField;
    private JPasswordField passwordField;

    public UserLogin() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setTitle("User Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.getContentPane().setLayout(null);
        
        JLabel lblId = new JLabel("ID:");
        lblId.setBounds(0, 12, 173, 36);
        frame.getContentPane().add(lblId);
        
        idField = new JTextField();
        idField.setBounds(222, 13, 184, 36);
        frame.getContentPane().add(idField);
        idField.setColumns(10);
        
        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(0, 79, 173, 36);
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        passwordField.setBounds(220, 80, 184, 36);
        frame.getContentPane().add(passwordField);
        
        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(145, 126, 150, 50);
        btnLogin.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                
                try {
                    if (DatabaseOperations.validatePassword(idField.getText(),
                                                            new String(passwordField.getPassword()))) {
                        frame.dispose();
                        Reservation reservation = new Reservation();
                        
                    } else {
                        JOptionPane.showMessageDialog(btnLogin, "ID or Password does not match","Invalid ID/Password",JOptionPane.ERROR_MESSAGE);
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnLogin);
        
        JButton btnRegister = new JButton("Register  ");
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
                Register register = new Register();
            }
        });
        
        JLabel lblNewUser = new JLabel("New User?");
        lblNewUser.setBounds(150, 175, 173, 36);
        frame.getContentPane().add(lblNewUser);
        btnRegister.setBounds(145, 208, 150, 50);
        frame.getContentPane().add(btnRegister);
        frame.setVisible(true);
    }
}

AdminPanel: This class provides the Admin Panel where admin can add buses,see various information in database and delete any required record from the database.

Code:

package org.ProjectGurukul;

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JTabbedPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JTable;

public class AdminPanel {

    private JFrame frame;
    private JTextField busIdfield;
    private JTextField busNoField;
    private JTextField bustypeField;
    private JTextField totalSeatsfield;
    private JTextField availableSeatsField;
    private JTextField depCityField;
    private JTextField arrCityField;
    private JTextField depTimeField;
    private JTextField arrTimeField;
    private JTextField farefield;
    private JTextField deletionIDfield;
    private JTable busTable;
    private JTable userTable;
    private JTable reservationTable;

    AdminPanel(){

        frame = new JFrame();
        frame.setBounds(100, 100, 611, 500);
        frame.setTitle("Admin Panel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
        
        JPanel deletePanel = new JPanel();
        frame.getContentPane().add(deletePanel);
        deletePanel.setLayout(new GridLayout(0, 3, 0, 0));
        
        JComboBox<String> tablesComboBox = new JComboBox<String>();
        tablesComboBox.addItem("bus");
        tablesComboBox.addItem("user");
        tablesComboBox.addItem("reservation");
        deletePanel.add(tablesComboBox);
        
        deletionIDfield = new JTextField();
        deletePanel.add(deletionIDfield);
        deletionIDfield.setColumns(10);
        
        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    DatabaseOperations.delete((String) tablesComboBox.getSelectedItem(),Integer.valueOf(deletionIDfield.getText()));
                    JOptionPane.showMessageDialog(deleteButton, "Deleted Successfully");
                    try {
                        DatabaseOperations.loadData((DefaultTableModel) busTable.getModel(),"buses");
                        DatabaseOperations.loadData((DefaultTableModel) reservationTable.getModel(),"reservations");
                        DatabaseOperations.loadData((DefaultTableModel) userTable.getModel(),"users");
                    } catch (SQLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                } catch (NumberFormatException e1) {
                    JOptionPane.showMessageDialog(deleteButton, "Invalid ID");
                    e1.printStackTrace();
                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(deleteButton, e1.getMessage());
                    e1.printStackTrace();
                }
            }
        });
        deletePanel.add(deleteButton);
        
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        frame.getContentPane().add(tabbedPane);
        
        JScrollPane busScrollPane = new JScrollPane();
        tabbedPane.addTab("Buses", null, busScrollPane, null);
        

        busTable = new JTable();
        busTable.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "ID", "no", "Type", "Total Seats", "Available", "Departure City", "Arrival City", "Departure Time", "Arrival Time","Fare"
            }
        ));
        busScrollPane.setViewportView(busTable);
        
        JScrollPane usersSrollPane = new JScrollPane();
        tabbedPane.addTab("Users", null, usersSrollPane, null);
        
        userTable = new JTable();
        userTable.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "Id", "Name", "E-Mail", "Password", "Phone No", "Address"
            }
        ));
        usersSrollPane.setViewportView(userTable);
        
        JScrollPane reservationsScrollPane = new JScrollPane();
        tabbedPane.addTab("Reservations", null, reservationsScrollPane, null);
        
        reservationTable = new JTable();
        reservationTable.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "ID", "User ID", "Bus ID", "Reserved Seats", "Total Fare", "Date"
            }
        ));
        reservationsScrollPane.setViewportView(reservationTable);
        
        JPanel busPanel = new JPanel();
        tabbedPane.addTab("Add Bus", null, busPanel, null);
        busPanel.setLayout(new GridLayout(0, 2, 0, 0));
        
        JLabel busIDLabel = new JLabel("Bus ID:");
        busPanel.add(busIDLabel);
        
        busIdfield = new JTextField();
        busIdfield.setColumns(10);
        busPanel.add(busIdfield);
        
        JLabel busNoLabel = new JLabel("Bus No:");
        busPanel.add(busNoLabel);
        
        busNoField = new JTextField();
        busNoField.setColumns(10);
        busPanel.add(busNoField);
        
        JLabel busTypeLabel = new JLabel("Bus Type:");
        busPanel.add(busTypeLabel);
        
        bustypeField = new JTextField();
        bustypeField.setColumns(10);
        busPanel.add(bustypeField);
        
        JLabel totalSeatsLable = new JLabel("Total Seats:");
        busPanel.add(totalSeatsLable);
        
        totalSeatsfield = new JTextField();
        totalSeatsfield.setColumns(10);
        busPanel.add(totalSeatsfield);
        
        JLabel availableSeatsLabel = new JLabel("Available Seats:");
        busPanel.add(availableSeatsLabel);
        
        availableSeatsField = new JTextField();
        availableSeatsField.setColumns(10);
        busPanel.add(availableSeatsField);
        
        JLabel departureCityLabel = new JLabel("Departure City:");
        busPanel.add(departureCityLabel);
        
        depCityField = new JTextField();
        depCityField.setColumns(10);
        busPanel.add(depCityField);
        
        JLabel arrivalCityLabel = new JLabel("Arrival City:");
        busPanel.add(arrivalCityLabel);
        
        arrCityField = new JTextField();
        arrCityField.setColumns(10);
        busPanel.add(arrCityField);
        
        JLabel depTimelable = new JLabel("Departure Time:");
        busPanel.add(depTimelable);
        
        depTimeField = new JTextField();
        depTimeField.setColumns(10);
        busPanel.add(depTimeField);
        
        JLabel arrTimeLable = new JLabel("Arrival Time:");
        busPanel.add(arrTimeLable);
        
        arrTimeField = new JTextField();
        arrTimeField.setColumns(10);
        busPanel.add(arrTimeField);
        
        JLabel fareLable = new JLabel("Fare:");
        busPanel.add(fareLable);
        
        farefield = new JTextField();
        farefield.setColumns(10);
        busPanel.add(farefield);
        
        JButton btnNewButton = new JButton("Add Bus");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    DatabaseOperations.addBus(Integer.valueOf(busIdfield.getText()),
                                              busNoField.getText(),
                                              bustypeField.getText(), 
                                              Integer.valueOf(totalSeatsfield.getText()), 
                                              Integer.valueOf(availableSeatsField.getText()), 
                                              depCityField.getText(), 
                                              arrCityField.getText(), 
                                              depTimeField.getText(), 
                                              arrTimeField.getText(), 
                                              Integer.valueOf(farefield.getText()));
                    DatabaseOperations.loadData((DefaultTableModel) busTable.getModel(),"buses");

                    JOptionPane.showMessageDialog(btnNewButton, "Bus added Successfully","Success",JOptionPane.INFORMATION_MESSAGE);

                } catch (NumberFormatException e1) {
                    JOptionPane.showMessageDialog(btnNewButton, "Please enter only Numeric value in ID\nSeats\nFare","Invalid Value",JOptionPane.ERROR_MESSAGE);
                        e1.printStackTrace();
                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(btnNewButton, "Can't Add the bus\n"+e1.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                }
            }
        });
        
        JLabel fareLable_1 = new JLabel("");
        busPanel.add(fareLable_1);
        busPanel.add(btnNewButton);
        frame.setVisible(true);
        
        try {
            DatabaseOperations.loadData((DefaultTableModel) busTable.getModel(),"buses");
            DatabaseOperations.loadData((DefaultTableModel) reservationTable.getModel(),"reservations");
            DatabaseOperations.loadData((DefaultTableModel) userTable.getModel(),"users");
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        
        
        
        
    }
}

Register: This class provides the User registration screen in our app where users can register themselves and set a password for login.

Code:

package org.ProjectGurukul;

import javax.swing.JFrame;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;

public class Register {
    private JFrame frame;
    private JTextField userIdField;
    private JLabel lblName;
    private JTextField nameField;
    private JLabel lblemail;
    private JTextField emailField;
    private JLabel lblPassword;
    private JPasswordField passwordField;
    private JLabel lblPhone;
    private JTextField phoneNumField;
    private JLabel lblAddress;
    private JTextField addressField;
    private JButton btnBack;
    private JButton btnRegister;
    
    public Register() {
        initialilze();
    }

    private void initialilze() {
        
        frame = new JFrame();
        frame.setBounds(100, 100, 598, 372);
        frame.setTitle("User Registration");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(0, 2, 5, 5));
        
        JLabel lblId = new JLabel("User ID:");
        frame.getContentPane().add(lblId);
        
        userIdField = new JTextField();
        frame.getContentPane().add(userIdField);
        userIdField.setColumns(10);
        
        lblName = new JLabel("Name:");
        frame.getContentPane().add(lblName);
        
        nameField = new JTextField();
        nameField.setColumns(10);
        frame.getContentPane().add(nameField);
        
        lblemail = new JLabel("Email:");
        frame.getContentPane().add(lblemail);
        
        emailField = new JTextField();
        emailField.setColumns(10);
        frame.getContentPane().add(emailField);
        
        lblPassword = new JLabel("Password");
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        frame.getContentPane().add(passwordField);
        
        lblPhone = new JLabel("Phone:");
        frame.getContentPane().add(lblPhone);
        
        phoneNumField = new JTextField();
        phoneNumField.setColumns(10);
        frame.getContentPane().add(phoneNumField);
        
        lblAddress = new JLabel("Address:");
        frame.getContentPane().add(lblAddress);
        
        addressField = new JTextField();
        addressField.setColumns(10);
        frame.getContentPane().add(addressField);
        
        btnBack = new JButton("Back ");
        btnBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
                UserLogin userLogin = new UserLogin();
            }
        });
        frame.getContentPane().add(btnBack);
        
        btnRegister = new JButton("Register");
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    DatabaseOperations.addUser(Integer.valueOf(userIdField.getText()), 
                                                   nameField.getText(), 
                                                   emailField.getText(), 
                                                   phoneNumField.getText(),
                                                   new String(passwordField.getPassword()), 
                                                   addressField.getText());
                    JOptionPane.showMessageDialog(btnRegister, "User Added Successfully", "Success", JOptionPane.INFORMATION_MESSAGE);

                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(btnRegister, "Can't Add User\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnRegister);
        frame.setVisible(true);
    }
}

Reservation: This class provides the User to Book their bus add the reservation is added into the database record

Code:

package org.ProjectGurukul;

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

public class Reservation {
    
    private JFrame frame;
    private JTextField idTextField;
    private JTextField dateField;
    
    
    public Reservation() {
        initialilze();
    }

    private void initialilze() {
        
        frame = new JFrame();
        frame.setBounds(100, 100, 611, 386);
        frame.setTitle("Reservation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(0, 2, 5, 5));
        
        JLabel lblID = new JLabel("ID:");
        frame.getContentPane().add(lblID);
        
        idTextField = new JTextField();
        frame.getContentPane().add(idTextField);
        idTextField.setColumns(10);
        
        JLabel lblUserID = new JLabel("User ID:");
        frame.getContentPane().add(lblUserID);
        
        JComboBox<String> uidcomboBox = new JComboBox<String>();
        frame.getContentPane().add(uidcomboBox);
        
        JLabel lblBusID = new JLabel("Bus ID/Route:");
        frame.getContentPane().add(lblBusID);
        
        JComboBox<String> bidcomboBox = new JComboBox<String>();
        frame.getContentPane().add(bidcomboBox);
        
        JLabel lblSeatCount = new JLabel("No. of Seats to Reserve:");
        frame.getContentPane().add(lblSeatCount);
        
        JSpinner seatSpinner = new JSpinner();
        seatSpinner.setModel(new SpinnerNumberModel(0, 0, 5, 1));
        
        frame.getContentPane().add(seatSpinner);
        
        JLabel lblTotalFare = new JLabel("Total Fare:");
        frame.getContentPane().add(lblTotalFare);
        
        JTextArea totalFareArea = new JTextArea();
        totalFareArea.setText("Rs.0");
        totalFareArea.setEditable(false);
        seatSpinner.addChangeListener(new ChangeListener() {
            
            @Override
            public void stateChanged(ChangeEvent e) {
                String id = (String)bidcomboBox.getSelectedItem();
                id = id.substring(0, id.indexOf("|"));
                try {
                    int totalFare = DatabaseOperations.getBusFare(Integer.valueOf(id)) * (Integer)seatSpinner.getValue();
                    totalFareArea.setText("Rs."+totalFare);
                } catch (NumberFormatException e1) {
                    e1.printStackTrace();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        });
        

        frame.getContentPane().add(totalFareArea);
        
        JLabel lbldate = new JLabel("Date:");
        frame.getContentPane().add(lbldate);
        
        dateField = new JTextField();
        dateField.setColumns(10);
        frame.getContentPane().add(dateField);
        
        JButton btnCheckDetails = new JButton("Check Reservation Detail");
        btnCheckDetails.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String[] data = DatabaseOperations.getReservation(Integer.valueOf(idTextField.getText()));
                    Ticket t =  new Ticket(data);
                } catch (NumberFormatException e1) {
                    JOptionPane.showMessageDialog(btnCheckDetails, "Invalid ID","Please enter a valid Id",JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                } catch (SQLException e1) {

                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnCheckDetails);
        
        JButton btnBook = new JButton("Book");
        btnBook.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String uid = (String)uidcomboBox.getSelectedItem();
                uid = uid.substring(0, uid.indexOf("|"));
                String bid = (String)bidcomboBox.getSelectedItem();
                bid = bid.substring(0, bid.indexOf("|"));
                try {
                    if((Integer)seatSpinner.getValue() > 0) {
                    DatabaseOperations.addReservation(Integer.valueOf(idTextField.getText()),
                                                        Integer.valueOf(uid),
                                                        Integer.valueOf(bid),
                                                        Integer.valueOf(totalFareArea.getText().substring(3)),
                                                        (Integer)seatSpinner.getValue(),
                                                        dateField.getText());
                    JOptionPane.showMessageDialog(btnBook,"Booked Successfully ","Success",JOptionPane.INFORMATION_MESSAGE);
                    }
                    else {
                        JOptionPane.showMessageDialog(btnBook,"At least select one seat","Error",JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException e1) {
                    JOptionPane.showMessageDialog(btnBook,"Please enter a valid ID ","Error",JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                } catch (SQLException e1) {
                    
                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnBook);
        frame.setVisible(true);
    
        try {
            DatabaseOperations.updateCombox("users",uidcomboBox);
            DatabaseOperations.updateCombox("buses",bidcomboBox);

        } catch (SQLException e1) {
            
            e1.printStackTrace();
        }
        
        
        
        
    
    }
}

Ticket: This class provides the reservation details to the users so the user can see their reservation details.

Code:

package org.ProjectGurukul;

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Ticket {
    
    private JFrame frame;

    public Ticket(String[] data) {
        frame = new JFrame();
        frame.setBounds(100, 100, 611, 386);
        frame.setTitle("Ticket Details");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(0, 2, 5, 5));	
        
        String[] colNames = {"Reservation ID:",
                            "User ID:",
                            "Bus ID:",
                            "Reserved Seats:",
                            "Total Fare:",
                            "Reservation Date:",
                            "Name:",
                            "Email:",
                            "Phone No.:",
                            "Address:",
                            "Bus No.:",
                            "Bus Type:",
                            "Total Seats",
                            "Availabe Seats:",
                            "Departure City:",
                            "Arrival City:",
                            "Departure Time:",
                            "Arrival Time:",
                            "Fare:"};
        for (int i = 0; i < data.length; i++) {
            frame.getContentPane().add(new JLabel(colNames[i] + data[i]));	
        }
        
        frame.setVisible(true);
        
        
        
        
    }

}

DatabaseOperations: This class provides access to the database and various methods to perform operations such as adding a new bus, adding a new user, retrieving the reservation data etc.

A brief explanation for some of the methods in this class

  • dbInit(): This method initializes the SQLite database and creates three tables in it: buses, users, and reservations. It first creates a SQLiteDataSource object and sets the URL of the database file. Then, it gets a connection to the database and creates the tables using SQL statements. Finally, it closes the connection.
  • addBus(int id,String number,String type,int seats,int availableSeats,String depCity,String arrCity,String depTime,String arrTime,int fare): This method adds a new bus to the buses table in the database. It takes in the parameters for the bus, creates a prepared statement with an SQL INSERT statement, sets the values of the parameters in the prepared statement, and executes the statement. Finally, it closes the connection.
  • getBusFare(int id): This method retrieves the fare of a bus with the given ID from the buses table in the database. It takes in the ID as a parameter, creates a prepared statement with an SQL SELECT statement, sets the ID parameter in the prepared statement, executes the statement, and retrieves the fare from the result set. Finally, it closes the connection and returns the fare.
  • addUser(int id,String name,String email,String password,String phone,String address): This method adds a new user to the users table in the database. It takes in the parameters for the user, creates a prepared statement with an SQL INSERT statement, sets the values of the parameters in the prepared statement, and executes the statement. Finally, it closes the connection.
  • validatePassword(String id,String password): This method retrieves the password of a user with the given ID from the users table in the database and validates it against the given password. It takes in the ID and password as parameters, creates a prepared statement with an SQL SELECT statement, sets the ID parameter in the prepared statement, executes the statement, retrieves the password from the result set, and compares it to the given password. Finally, it closes the connection and returns a boolean indicating whether the passwords match or not.
  • getBusList(JComboBox comboBox): This method retrieves a list of all buses from the buses table in the database and populates a JComboBox with the bus numbers. It creates a prepared statement with an SQL SELECT statement, executes the statement, retrieves the bus numbers from the result set, and adds them to the combo box. Finally, it closes the connection.
  • getReservationList(int userId): This method retrieves a list of all reservations made by a user with the given ID from the reservations table in the database and returns a TableModel object representing the data. It creates a prepared statement with an SQL SELECT statement that joins the reservations and buses tables and retrieves the relevant data, sets the user ID parameter in the prepared statement, executes the statement, retrieves the data from the result set, and creates a DefaultTableModel object with the data. Finally, it closes the connection and returns the TableModel.

Code for this class:

package org.ProjectGurukul;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import org.sqlite.SQLiteDataSource;

public class DatabaseOperations {
//	declaring connection and dataSource variables
    private static Connection conn;
    private static SQLiteDataSource ds;
    
//	initialize method to initialize the database with all the tables
    public static void dbInit() {
        ds = new SQLiteDataSource();
        
        try {
            ds = new SQLiteDataSource();
            ds.setUrl("jdbc:sqlite:BusDB.db");
        } catch ( Exception e ) {
            e.printStackTrace();
            
            System.exit(0);
        }
        try {
        	 conn = ds.getConnection();
        	 
        	 Statement statement = conn.createStatement();
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS buses (\n"
             		+ "    bus_id INTEGER PRIMARY KEY,\n"
             		+ "    bus_number TEXT NOT NULL,\n"
             		+ "    bus_type TEXT NOT NULL,\n"
             		+ "    total_seats INTEGER NOT NULL,\n"
             		+ "    available_seats INTEGER NOT NULL,\n"
             		+ "    departure_city TEXT NOT NULL,\n"
             		+ "    arrival_city TEXT NOT NULL,\n"
             		+ "    departure_time TEXT NOT NULL,\n"
             		+ "    arrival_time TEXT NOT NULL,\n"
             		+ "    fare INTEGER NOT NULL\n"
             		+ ");\n"
             		);
            
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n"
             		+ "    user_id INTEGER PRIMARY KEY,\n"
             		+ "    name TEXT NOT NULL,\n"
             		+ "    email TEXT NOT NULL UNIQUE,\n"
             		+ "    password TEXT NOT NULL,\n"
             		+ "    phone_number TEXT NOT NULL,\n"
             		+ "    address TEXT NOT NULL\n"
             		+ ");"
              		);
             
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS reservations (\n"
             		+ "    reservation_id INTEGER PRIMARY KEY,\n"
             		+ "    user_id INTEGER NOT NULL,\n"
             		+ "    bus_id INTEGER NOT NULL,\n"
             		+ "    reserved_seats INTEGER NOT NULL,\n"
             		+ "    total_fare INTEGER NOT NULL,\n"
             		+ "    reservation_date TEXT NOT NULL,\n"
             		+ "    FOREIGN KEY(user_id) REFERENCES users(user_id),\n"
             		+ "    FOREIGN KEY(bus_id) REFERENCES buses(bus_id)\n"
             		+ ");"
               		);
             
             
//           Closing statement and connection  
             statement.close();
        	 conn.close();
        	 
        }catch ( SQLException e ) {
            e.printStackTrace();
            System.exit( 0 );
        }
        finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            }catch (SQLException e) {
                System.err.println(e);
              }
        
        }
    

    }

    /*
     * ----------------------------------- Bus Operations--------------------------------------------------------
     * 
     */
//	Method to add Buses into the database
    public static void addBus(int id,String number,String type,int seats,int availableSeats,
                                String depCity,String arrCity,String depTime,String arrTime,int fare) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                                                    + "buses(bus_id,bus_number,bus_type,total_seats,available_seats,"
                                                    + "departure_city,arrival_city,departure_time,arrival_time,fare) "
                                                    + "VALUES(?,?,?,?,?,?,?,?,?,?)");
        ps.setInt(1, id);
        ps.setString(2, number);
        ps.setString(3, type);
        ps.setInt(4, seats);
        ps.setInt(5, availableSeats);
        ps.setString(6, depCity);
        ps.setString(7, arrCity);
        ps.setString(8, depTime);
        ps.setString(9, arrTime);
        ps.setInt(10, fare);
        
        ps.executeUpdate();
        ps.close();
        conn.close();
        
    }
    
//	Method to fetch Bus data from the database
    public static int getBusFare(int id) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("SELECT fare FROM buses WHERE bus_id ="+id+";");
        
        ResultSet rs = ps.executeQuery();
        int fare =  rs.getInt("fare");
        
        rs.close();
        ps.close();
        conn.close();
        return fare;

        
    }
    
    /*
     * ----------------------------------- User Operations--------------------------------------------------------
     */
    
    //	Method to add User into the database
    public static void addUser(int id,String name,String email,String password,String phone,String address) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                                                    + "users(user_id,name,email,password,phone_number,address)"
                                                    + "VALUES(?,?,?,?,?,?)");
        ps.setInt(1, id);
        ps.setString(2, name);
        ps.setString(3, email);
        ps.setString(5, password);
        ps.setString(4, phone);
        ps.setString(6, address);
        
        ps.executeUpdate();
        ps.close();
        conn.close();
    }
    
//	Method to fetch Email and Password from the database and validate it 
    public static boolean validatePassword(String id,String password) throws SQLException {
        conn = ds.getConnection();
        String sql = "SELECT user_id,password FROM users WHERE user_id = ?;";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,id );
        ResultSet rs =  ps.executeQuery();
        
        
        if (id.equals(rs.getString("user_id"))  && password.equals(rs.getString("password"))) {
            rs.close();
            ps.close();
            conn.close();
            return true;
        }
        
        rs.close();
        ps.close();
        conn.close();
        return false;
    }
    

    /*
     * ----------------------------------- Reservations Operations--------------------------------------------------------
     */
//	Method to add Reservation into the database
    public static void addReservation(int id,int userID,int busID,int reservedSeats,int totalFare,String reservationDate)throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                                                    + "reservations(reservation_id,user_id,bus_id,reserved_seats,total_fare,reservation_date)"
                                                    + "VALUES(?,?,?,?,?,?);");
        ps.setInt(1, id);
        ps.setInt(2, userID);
        ps.setInt(3, busID);
        ps.setInt(5, reservedSeats);
        ps.setInt(4, totalFare);
        ps.setString(6, reservationDate);
        
        ps.executeUpdate();
        ps.close();
        conn.close();
    }

//	Method to fetch Reservation data from the database
    public static String[] getReservation(int id) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("SELECT reservation_id,users.user_id,buses.bus_id,\n"
                + "reserved_seats,total_fare,\n"
                + "reservation_date,name,email,phone_number,\n"
                + "address,bus_number,bus_type,total_seats,\n"
                + "available_seats,departure_city,arrival_city,\n"
                + "departure_time,arrival_time,fare\n"
                + "\n"
                + "  from reservations \n"
                + "INNER join buses on\n"
                + "reservations.bus_id = buses.bus_id\n"
                + "INNER join users on\n"
                + "reservations.user_id = users.user_id "
                + "WHERE reservation_id = ? ;");
        ps.setInt(1, id);
        
        ResultSet rs = ps.executeQuery(); 
        String[] data = new String[18];
        
        for (int j = 0; j < data.length; j++) {
            data[j] = rs.getString(j+1);
        }
        
    
        
        
        ps.close();
        conn.close();
        return data;
        
    }
    
//	Method to update the comboBoxes with data from the database
    public static void updateCombox(String table,JComboBox<String> cbx) throws SQLException {
        cbx.removeAll();
        conn = ds.getConnection();
        String sql = "SELECT * FROM "+table+";";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if(table.equals("users")) {
            while(rs.next()) {
                cbx.addItem(rs.getString("user_id") +"|"+ rs.getString("name"));
            }
        }
        else {
            while(rs.next()) {
                cbx.addItem(rs.getString("bus_id") +"|"+ rs.getString("departure_city")+">"+rs.getString("arrival_city"));
            }
        }
        rs.close();
        ps.close();
        conn.close();

    }

//	Method to delete any specific record from a specific table 
    public static void delete(String table,int id) throws SQLException {
        conn = ds.getConnection();
        String sql = "DELETE  FROM "+table+"s WHERE "+table+"_id = ?";
        if (table.equals("bus")) {
             sql = "DELETE  FROM buses WHERE "+table+"_id = ?";
        }
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        ps.executeUpdate();
        
        ps.close();
        conn.close();
    }
    
//	Method to Load Data from the database into the table
    public static void loadData(DefaultTableModel model,String table) throws SQLException {
        model.setRowCount(0);
        conn = ds.getConnection();
        String sql = "SELECT * FROM "+table+";";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        Object[] row = new Object[model.getColumnCount()]; 
        while (rs.next()) {
            for (int i = 0; i < row.length; i++) {
                row[i] = rs.getObject(i+1);
            }
            model.addRow(row);

        }
        ps.close();
        conn.close();
    }
}

Output:

bus reservation output

java bus reservation output

java bus reservation project output

bus reservation system project output

Summary:

In this project, we created a fully functional Bus Reservation System using Java Swing library, which includes two modules – Admin and User. We learned how to implement various features in both modules, such as adding and deleting reservations, buses, and users.

Additionally, we also learn how to allow customers to add their reservations, check their details, and register new customers. We used various SQL queries and used java libraries to interact with them.

Leave a Reply

Your email address will not be published. Required fields are marked *