Java Hospital Management – Saving Time and Lives with Our System

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

Welcome to this project on building a hospital management system using Java Swing library and SQLite. The system consists of five tabs – Appointment, Prescription, Medication, Patients, and Doctors. Each of these tabs has a table to display corresponding data, as well as an input panel to input data.

The system also includes two buttons – “Remove” and “Show All”. The “Remove” button allows users to remove data from the database, while the “Show All” button loads all the database data into the table. The use of SQLite as the database management system ensures that the data is stored securely and can be accessed quickly and easily.

By the end of this project, you will have a better understanding of how to create a hospital management system using Java Swing library and SQLite, and how to implement different functionalities in the system. So, let’s get started!

About Java Hospital Management System

The objective of this project is to provide a step-by-step guide on how to create an Hospital Management System using Java, Java Swing, SQLite, and Eclipse IDE.T

By the end of this project, you will have a clear understanding of how to create a system with the ability to manage patient data, appointments, prescriptions, medications, doctors, and more. Additionally, you will learn how to implement features such as input panels, tables, and database management.

Prerequisites for Hospital Management System using Java

To complete this project, you should have:

  • Basic Java programming skills
  • Knowledge of Java Swing for GUI development
  • SQL database knowledge and SQL query skills
  • Understanding of JAR files in Java projects
  • Basic database management knowledge, including SQLite
  • A Java IDE, such as Eclipse
    Optionally, experience with the WindowBuilder plugin in Eclipse to make GUI design easier.

Download Java Hospital Management System Project

Please download the source code of java hospital management system project: Java Hospital Management System Project Code

  • Language used: Java
  • Coding Tool used: Eclipse IDE
  • Type: Desktop Application
  • Database used: SQLite Database

Steps to Create Hospital Management System using Java

Following are the steps for developing the Java Hospital Management System project:

Step 1: Setting Up the Project and Classes in Eclipse

  1. Launch Eclipse and go to “File” > “New” > “Java Project”.
  2. Give the project a name, such as “Hospital Management System”.
  3. Right-click on the project and select “New” > “Class”.
  4. Name the first class, for example, “HospitalManagement”.
  5. Repeat steps 3 and 4 to create another class, such as “Database”.

Step 2: Adding SQLite to the Project in Eclipse

  1. Go to the Project Explorer in Eclipse and right-click on your project.
  2. Select “Properties” from the menu.
  3. In the Properties window, navigate to “Java Build Path” and click the “Libraries” tab.
  4. Click the “Add External JARs” button and find the SQLite JAR file.
  5. Choose the JAR file and press “Open”.
  6. Click “OK” to close the Properties window.

Note: Before moving forward, make sure to have the SQLite JAR file downloaded and saved on your computer. This file can be found on MavenRepository if needed. Incorporating SQLite into your Eclipse project is now complete after following the steps outlined above.

Step 3: Implementing the Database class

Here’s the complete code for the database class we created:

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 Database {
//	declaring connection and datasource variables
  static Connection conn;
  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:HospitalDB.db");
        } catch ( Exception e ) {
            e.printStackTrace();
            
            System.exit(0);
        }
        try {
        	 conn = ds.getConnection();
        	 
        	 Statement statement = conn.createStatement();
        	 // Create the Patients table
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS patients (\n"
             		+ "  patient_id INTEGER PRIMARY KEY,\n"
             		+ "  name TEXT NOT NULL,\n"
             		+ "  gender TEXT NOT NULL,\n"
             		+ "  age INTEGER NOT NULL,\n"
             		+ "  address TEXT NOT NULL,\n"
             		+ "  phone_number TEXT NOT NULL\n"
             		+ ");");
             
            
             
             // Create the Doctors table
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS doctors (\n"
             		+ "  doctor_id INTEGER PRIMARY KEY,\n"
             		+ "  name TEXT NOT NULL,\n"
             		+ "  gender TEXT NOT NULL,\n"
             		+ "  specialization TEXT NOT NULL,\n"
             		+ "  phone_number TEXT NOT NULL\n"
             		+ ");");
             
           
             // Create the Appointments table
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS appointments (\n"
             		+ "  appointment_id INTEGER PRIMARY KEY,\n"
             		+ "  patient TEXT NOT NULL,\n"
             		+ "  doctor TEXT INTEGER NOT NULL,\n"
             		+ "  appointment_date TEXT NOT NULL,\n"
             		+ "  appointment_time TEXT NOT NULL\n"
             		+ ");"
             		);
             
             // Create the Medications table
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS medications (\n"
             		+ "  medication_id INTEGER PRIMARY KEY,\n"
             		+ "  name TEXT NOT NULL,\n"
             		+ "  dosage TEXT NOT NULL\n"
             		+ ");");
             
             //Create the Prescriptions table
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS prescriptions (\n"
             		+ "  prescription_id INTEGER PRIMARY KEY,\n"
             		+ "  patient_id INTEGER NOT NULL,\n"
             		+ "  doctor_id INTEGER NOT NULL,\n"
             		+ "  medication_id INTEGER NOT NULL,\n"
             		+ "  start_date TEXT NOT NULL,\n"
             		+ "  end_date TEXT NOT NULL,\n"
             		+ "  FOREIGN KEY (patient_id) REFERENCES patients (patient_id),\n"
             		+ "  FOREIGN KEY (doctor_id) REFERENCES doctors (doctor_id),\n"
             		+ "  FOREIGN KEY (medication_id) REFERENCES medications (medication_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);
              }
        
        }
  

  }
  
//	Method to add new Doctors into the database
  protected static void addDoctor(int id,String name,String gender,String specialization,String phone_number) throws SQLException{
    conn = ds.getConnection();
    PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                          + "doctors(doctor_id,name,gender,specialization,phone_number) "
                          + "VALUES(?,?,?,?,?)");
    ps.setInt(1, id);
    ps.setString(2, name);
    ps.setString(3, gender);
    ps.setString(4, specialization);
    ps.setString(5, phone_number);
    ps.executeUpdate();
    ps.close();
    conn.close();
  }
//	Method to load doctor's data to the table
  public static void loadDocData(DefaultTableModel model) throws SQLException {
    model.setRowCount(0);
    conn = ds.getConnection();
    String query = "SELECT * From doctors";
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
 		// Add data to the table model
    while (rs.next()) {
        int id = rs.getInt("doctor_id");
        String name = rs.getString("name");
        String gender = rs.getString("gender");
        String specialization = rs.getString("specialization");
        String phnum = rs.getString("phone_number");

        Object[] row = {id, name, gender,specialization,phnum};
        model.addRow(row);
    }
    rs.close();
    ps.close();
    conn.close();
    
  }

//  Method to add new Patient in the database
  public static void addPatient(int id,String name,String gender,int age,String address ,String phone_number) throws SQLException {
    conn = ds.getConnection();
    PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                          + "patients(patient_id,name,gender,age,address,phone_number) "
                          + "VALUES(?,?,?,?,?,?)");
    ps.setInt(1, id);
    ps.setString(2, name);
    ps.setString(3, gender);
    ps.setInt(4, age);
    ps.setString(5, address);
    ps.setString(6, phone_number);
    ps.executeUpdate();
    ps.close();
    conn.close();
    
    
  }
  
//	Method to load Patients data to the table
  public static void loadPatData(DefaultTableModel model) throws SQLException {
    model.setRowCount(0);
    conn = ds.getConnection();
    String query = "SELECT * From patients";
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
 		// Add data to the table model
    while (rs.next()) {
        int id = rs.getInt("patient_id");
        String name = rs.getString("name");
        String gender = rs.getString("gender");
        int age= rs.getInt("age");
        String address = rs.getString("address");
        String phnum = rs.getString("phone_number");

        Object[] row = {id, name, gender,age,address,phnum};
        model.addRow(row);
    }
    rs.close();
    ps.close();
    conn.close();
    
  }
//	Method to update the combo box with either the patient or doctors name
  public static void updateComboBox(JComboBox<String> cbx,String tableName) throws SQLException {
    cbx.removeAllItems();
    conn = ds.getConnection();
    String query = "SELECT "+tableName+"_id,name FROM "+tableName+"s;"; 
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs =  ps.executeQuery();
    
    while (rs.next()) {
      cbx.addItem(rs.getString(tableName+"_id")+ "|" + rs.getString("name"));
      
    }
    ps.close();
    conn.close();
    
  }
  
//Method to add new Medication to the medications table
  public static void addMedication(int id,String name,String dosage) throws SQLException {
    conn = ds.getConnection();
    String query = "INSERT INTO medications(medication_id,name,dosage) VALUES(?,?,?)";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setInt(1, id);
    ps.setString(2, name);
    ps.setString(3, dosage);
    ps.executeUpdate();
    ps.close();
    conn.close();
  }
// Method to load Medication data into the model
  public static void loadMedData(DefaultTableModel model) throws SQLException {
    model.setRowCount(0);
    conn = ds.getConnection();
    String query = "SELECT * From medications";
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
 		// Add data to the table model
    while (rs.next()) {
        int id = rs.getInt("medication_id");
        String name = rs.getString("name");
        String dosage = rs.getString("dosage");

        Object[] row = {id, name, dosage};
        model.addRow(row);
    }
    rs.close();
    ps.close();
    conn.close();
  }

//	Method to delete a specific value from a specific table
  public static void delete(String id, String table) throws SQLException {
    conn = ds.getConnection();
    String query = "DELETE FROM "+table+"s WHERE "+table+"_id = ?";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, id);
    ps.executeUpdate();
    ps.close();
    conn.close();
  }

//	Method to add the prescription data to the prescription table
  public static void addPresc(Integer id, String meds, String start, String end, String patient,
      String doctor) throws SQLException {
    conn = ds.getConnection();
    PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                          + "prescriptions(prescription_id,patient_id,doctor_id,medication_id,start_date,end_date) "
                          + "VALUES(?,?,?,?,?,?)");
    
    meds = meds.substring(0, meds.indexOf("|"));
    patient = patient.substring(0, patient.indexOf("|"));
    doctor = doctor.substring(0, doctor.indexOf("|"));
    ps.setInt(1, id);
    ps.setInt(2, Integer.valueOf(patient));
    ps.setInt(3, Integer.valueOf(doctor));
    ps.setInt(4, Integer.valueOf(meds));
    ps.setString(5, start);
    ps.setString(6, end);
    ps.executeUpdate();
    ps.close();
    conn.close();
  }

  
  
//  Method to load the prescripton data into the table model
  public static void loadPrescData(DefaultTableModel model) throws SQLException {
    model.setRowCount(0);
    conn = ds.getConnection();
    String query = "SELECT *,"
            + "patients.name AS pname,"
            + "doctors.name AS dname,"
            + "medications.name AS mname "
            + "From prescriptions "
            + "INNER JOIN patients ON patients.patient_id = prescriptions.patient_id "
            + "INNER JOIN doctors ON doctors.doctor_id = prescriptions.doctor_id "
            + "INNER JOIN medications ON medications.medication_id= prescriptions.medication_id ;";
    
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
 		// Add data to the table model
    while (rs.next()) {
        int id = rs.getInt("prescription_id");
        String patient = rs.getInt("patient_id")+"|"+rs.getString("pname");
        String doctor = rs.getInt("doctor_id")+"|"+rs.getString("dname");
        String med = rs.getInt("medication_id")+"|"+rs.getString("mname");
        String dosage = rs.getString("dosage");
        String start = rs.getString("start_date");
        String end = rs.getString("end_date");
        Object[] row = {id,patient,doctor,med,dosage,start,end};
        model.addRow(row);
    }
    rs.close();
    ps.close();
    conn.close();
  }
  
//	Method to load the appointment data into the table model
  public static void loadAptmtData(DefaultTableModel model) throws SQLException {
    model.setRowCount(0);
    conn = ds.getConnection();
    String query = "SELECT * From appointments";
    PreparedStatement ps = conn.prepareStatement(query);
    ResultSet rs = ps.executeQuery();
 		// Add data to the table model
    while (rs.next()) {
        int id = rs.getInt("appointment_id");
        String date = rs.getString("appointment_date");
        String time = rs.getString("appointment_time");
        String patient = rs.getString("patient");
        String doctor = rs.getString("doctor");
        Object[] row = {id,date,time,patient,doctor };
        model.addRow(row);
    }
    rs.close();
    ps.close();
    conn.close();
  }

//	Method to add the appointment data into the database
  public static void addAptmt(Integer id, String date, String time, String patient, String doctor) throws SQLException {
    conn = ds.getConnection();
    PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                          + "appointments(appointment_id,appointment_date,appointment_time,patient,doctor) "
                          + "VALUES(?,?,?,?,?)");
    
    
    ps.setInt(1, id);
    ps.setString(2, date);
    ps.setString(3,time);
    ps.setString(4,patient);
    ps.setString(5, doctor);
    
    ps.executeUpdate();
    ps.close();
    conn.close();
    
  }
  

}
  • dbInit(): This method initializes the database by creating all the necessary tables in the SQLite database. The method first creates a new SQLiteDataSource object and sets its URL to the location where the SQLite database file is located. It then establishes a connection to the database using the getConnection() method of the SQLiteDataSource object. After establishing a connection, it creates the following tables using SQL queries:
  • patients: This table has columns for patient ID, name, gender, age, address, and phone number.
  • doctors: This table has columns for doctor ID, name, gender, specialization, and phone number.
  • appointments: This table has columns for appointment ID, patient name, doctor ID, appointment date, and appointment time.
  • medications: This table has columns for medication ID, medication name, and dosage.
  • prescriptions: This table has columns for prescription ID, patient ID, doctor ID, medication ID, start date, and end date. It also has foreign key constraints that enforce referential integrity between the patients, doctors, and medications tables. After creating all the necessary tables, the method closes the connection to the database.

addDoctor(int id, String name, String gender, String specialization, String phone_number): This method adds a new doctor to the doctors table in the SQLite database. The method takes in parameters for the doctor’s ID, name, gender, specialization, and phone number, and uses a prepared statement to insert these values into the doctors table. The method then closes the prepared statement and the database connection.

loadDocData(DefaultTableModel model): This method loads data from the doctors table in the SQLite database and populates it into a JTable component using a DefaultTableModel. The method first sets the row count of the DefaultTableModel to 0 to clear any existing data. It then establishes a connection to the database using the getConnection() method of the SQLiteDataSource object. It creates a SQL query to select all data from the doctors table, creates a prepared statement using the SQL query, and executes the prepared statement using the executeQuery() method. The method then loops through the result set returned by the prepared statement and adds each row of data to the DefaultTableModel. Finally, the method closes the result set, the prepared statement, and the database connection.

addPatient(int id, String name, String gender, int age, String address, String phone_number): This method adds a new patient to the patients table in the SQLite database. The method takes in parameters for the patient’s ID, name, gender, age, address, and phone number, and uses a prepared statement to insert these values into the patients table. The method then closes the prepared statement and the database connection.

loadPatientData(DefaultTableModel model): This method loads data from the patients table in the SQLite database and populates it into a JTable component using a DefaultTableModel. The method first sets the row count of the DefaultTableModel to 0 to clear any existing data. It then establishes a connection to the database using the getConnection() method of the SQLiteDataSource object. It creates a SQL query to select all data from the patients table, creates a prepared statement using the SQL query, and executes the prepared statement using the executeQuery() method. The method then loops through the result set returned by the prepared statement and adds each row of data to the DefaultTableModel. Finally, the method closes the result set, the prepared statement and connection.

Similar methods are Implemented to load from the database to display it on the jtable and add data to the database.

delete(String id, String table): This method takes two parameters id and table, and constructs an query to delete the specified row with corresponding id passed into the parameter from the given table

updateComboBox(JComboBox<String> cbx,String tableName): This method is used to update the JComboBoxes with the new values inserted into the database or to simply load the data into the boxes. It creates a query with tableName to select id and name or the specific table and add the data as a string into the combo box as selectable items separated by a ‘|’.

Step 4: Implementing the HospitalManagement class

Here’s the complete code for the HospitalManagement class :

package org.ProjectGurukul;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;
import javax.swing.border.LineBorder;
import java.awt.GridLayout;
import java.awt.Panel;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class HospitalManagement {

  private JFrame frame;
  private JTextField patientnameField;
  private JTextField patientIDfield;
  private JTextField patientNumField;
  private JTextField patientAgefield;
  private JTextField patientAddressField;
  private JTextField appointmentIDField;
  private JTextField appointmentDateField;
  private JTextField appointmentTimeField;
  private JTextField docNameField;
  private JTextField docIDField;
  private JTextField docNumField;
  private JTextField docSpecialfield;
  private JTextField prescriptionIDfield;
  private JTextField startDateField;
  private JTextField endDateField;
  private JTable docTable;
  private JTable patTable;
  private JTable prescTable;
  private JTextField medIDfield;
  private JTextField medsNameField;
  private JTextField medsDoseField;
  private JTable medTable;
  private JTable aptmtTable;

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

  /**
   * Create the application.
   */
  public HospitalManagement() {
    Database.dbInit();
    initialize();
  }

  /**
   * Initialize the contents of the frame.
   */
  private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 800, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setTitle("Hospital Management System by ProjectGurukul");
    frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS));
    
    Color bgColor = Color.decode("#fefae0");
    
//		Creating a tabbed pane to hold different panels
    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    frame.getContentPane().add(tabbedPane);
    tabbedPane.setBackground(bgColor);

    /*---------------------------------------------Appointment Panel-----------------------------------------------------------------------*/
    JPanel appointmentsPanel = new JPanel();
    tabbedPane.addTab("Appointments", null, appointmentsPanel, null);
    appointmentsPanel.setBackground(bgColor);
    appointmentsPanel.setLayout(null);
    
    
    
    JPanel aptmtInputPanel = new JPanel();
    aptmtInputPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 5), "Add Appointment", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    aptmtInputPanel.setBackground(new Color(254, 250, 224));
    aptmtInputPanel.setBounds(12, 67, 349, 362);
    appointmentsPanel.add(aptmtInputPanel);
    aptmtInputPanel.setLayout(new GridLayout(0, 2, 0, 10));
    
    JLabel lblID = new JLabel("ID");
    aptmtInputPanel.add(lblID);
    
    appointmentIDField = new JTextField();
    aptmtInputPanel.add(appointmentIDField);
    appointmentIDField.setColumns(10);
    
    JLabel lblDate = new JLabel("Date");
    aptmtInputPanel.add(lblDate);
    
    appointmentDateField = new JTextField();
    aptmtInputPanel.add(appointmentDateField);
    appointmentDateField.setColumns(10);
    
    JLabel lblTime = new JLabel("Time");
    aptmtInputPanel.add(lblTime);
    
    appointmentTimeField = new JTextField();
    aptmtInputPanel.add(appointmentTimeField);
    appointmentTimeField.setColumns(10);
    
    JLabel lblPatient = new JLabel("Patient");
    aptmtInputPanel.add(lblPatient);
    
    JComboBox<String> patientsComboBox = new JComboBox<String>();
    aptmtInputPanel.add(patientsComboBox);
    
    JLabel lblDoctor = new JLabel("Doctor");
    aptmtInputPanel.add(lblDoctor);
    
    JComboBox<String> docComboBox = new JComboBox<String>();
    aptmtInputPanel.add(docComboBox);
    
    
    
    JButton btnaddAppointment = new JButton("Add");
    btnaddAppointment.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          Database.addAptmt(Integer.valueOf(appointmentIDField.getText()),
                            appointmentDateField.getText(),
                            appointmentTimeField.getText(),
                            patientsComboBox.getSelectedItem().toString(),
                            docComboBox.getSelectedItem().toString()
              );
        } catch (NumberFormatException e1) {
          JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);

          e1.printStackTrace();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
    });
    aptmtInputPanel.add(btnaddAppointment);
    btnaddAppointment.setBackground(new Color(188, 108, 37));
    
    JButton btnRemoveAppointment = new JButton("Remove");
    btnRemoveAppointment.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.delete(appointmentIDField.getText(),"appointment");
        } catch (SQLException e1) {
          JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);

          e1.printStackTrace();
        }
        
      }
    });
    aptmtInputPanel.add(btnRemoveAppointment);
    btnRemoveAppointment.setBackground(new Color(188, 108, 37));
    
    JScrollPane aptmtScrollpane = new JScrollPane();
    aptmtScrollpane.setBounds(364, 67, 419, 363);
    appointmentsPanel.add(aptmtScrollpane);
    
    aptmtTable = new JTable();
    String[] aptmtColumns = {"ID","Date","Time","Patient","Doctor"};
    DefaultTableModel aptmtModel =new DefaultTableModel(aptmtColumns,0);
    aptmtTable.setModel(aptmtModel);
    aptmtScrollpane.setViewportView(aptmtTable);
    

    JButton btnloadAptmtData = new JButton("Show All");
    btnloadAptmtData.setBackground(new Color(188, 108, 37));
    btnloadAptmtData.setBounds(376, 29, 100, 30);
    btnloadAptmtData.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.loadAptmtData(aptmtModel);
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
        
      }
    });
    appointmentsPanel.add(btnloadAptmtData);
    
    
    /*---------------------------------------------Prescription Panel-----------------------------------------------------------------------*/
    JPanel prescriptionsPanel = new JPanel();
    tabbedPane.addTab("Prescriptions", null, prescriptionsPanel, null);
    prescriptionsPanel.setBackground(bgColor);
    prescriptionsPanel.setLayout(null);
    
    JPanel prescriptionInputPanel = new JPanel();
    prescriptionInputPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 5), "Add Prescription", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    prescriptionInputPanel.setBackground(new Color(254, 250, 224));
    prescriptionInputPanel.setBounds(37, 0, 735, 129);
    prescriptionsPanel.add(prescriptionInputPanel);
    prescriptionInputPanel.setLayout(new GridLayout(0, 4, 0, 10));
    
    JLabel lblIDpres = new JLabel("ID");
    prescriptionInputPanel.add(lblIDpres);
    
    prescriptionIDfield = new JTextField();
    prescriptionIDfield.setColumns(10);
    prescriptionInputPanel.add(prescriptionIDfield);
    
    JLabel lblMedication = new JLabel("Medication");
    prescriptionInputPanel.add(lblMedication);
    
    JComboBox<String> medicationComboBox = new JComboBox<String>();
    prescriptionInputPanel.add(medicationComboBox);
    
    JLabel lblstrtDate = new JLabel("Start Date");
    prescriptionInputPanel.add(lblstrtDate);
    
    startDateField = new JTextField();
    startDateField.setColumns(10);
    prescriptionInputPanel.add(startDateField);
    
    JLabel lblEndDate = new JLabel("End Date");
    prescriptionInputPanel.add(lblEndDate);
    
    endDateField = new JTextField();
    endDateField.setColumns(10);
    prescriptionInputPanel.add(endDateField);
    
    JLabel lblPatient_1 = new JLabel("Patient");
    prescriptionInputPanel.add(lblPatient_1);
    
    JComboBox<String> prescPatientsComboBox = new JComboBox<String>();
    prescriptionInputPanel.add(prescPatientsComboBox);
    
    JLabel lblDoctor_1 = new JLabel("Doctor");
    prescriptionInputPanel.add(lblDoctor_1);
    
    JComboBox<String> prescDocComboBox = new JComboBox<String>();
    prescriptionInputPanel.add(prescDocComboBox);
    
    JScrollPane prescScrollPane = new JScrollPane();
    prescScrollPane.setBounds(36, 188, 725, 248);
    prescriptionsPanel.add(prescScrollPane);
    
    prescTable = new JTable();
    String[] prescColumns = {"ID","Patient","Doctor","Medication","Dosage","Start Date","End Date"};
    DefaultTableModel prescModel = new DefaultTableModel(prescColumns,0);
    prescTable.setModel(prescModel);
    
        prescScrollPane.setViewportView(prescTable);
        
        JButton btnaddPresc = new JButton("Add");
        btnaddPresc.setBounds(36, 129, 179, 27);
        prescriptionsPanel.add(btnaddPresc);
        btnaddPresc.setBackground(new Color(188, 108, 37));
        btnaddPresc.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.addPresc(
                  Integer.valueOf(prescriptionIDfield.getText()),
                  medicationComboBox.getSelectedItem().toString(),
                  startDateField.getText(),
                  endDateField.getText(),
                  prescPatientsComboBox.getSelectedItem().toString(),
                  prescDocComboBox.getSelectedItem().toString()
                  );
            } catch (NumberFormatException e1) {
              e1.printStackTrace();
              JOptionPane.showMessageDialog(prescriptionInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);

            } catch (SQLException e1) {
              e1.printStackTrace();
            }
            
          }
        });
        
        JButton btnRemovePresc = new JButton("Remove");
        btnRemovePresc.setBounds(227, 129, 179, 27);
        btnRemovePresc.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.delete(prescriptionIDfield.getText(),"prescription");
            } catch (SQLException e1) {
              JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);

              e1.printStackTrace();
            }
            
          }
        });
        prescriptionsPanel.add(btnRemovePresc);
        btnRemovePresc.setBackground(new Color(188, 108, 37));
        
        JButton btnLoadPrescData = new JButton("Show All");
        btnLoadPrescData.setBackground(new Color(188, 108, 37));
        btnLoadPrescData.setBounds(418, 130, 179, 27);
        btnLoadPrescData.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.loadPrescData(prescModel);
            } catch (SQLException e1) {
              
              e1.printStackTrace();
            }
            
          }
        });
        prescriptionsPanel.add(btnLoadPrescData);
    
/*---------------------------------------------Medications Panel-----------------------------------------------------------------------*/
    JPanel medicationsPanel = new JPanel();
    medicationsPanel.setLayout(null);
    medicationsPanel.setBackground(new Color(254, 250, 224));
    tabbedPane.addTab("Medications", null, medicationsPanel, null);
    
    JPanel medicInputPanel = new JPanel();
    medicInputPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 5), "Add Medications", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    medicInputPanel.setBackground(new Color(254, 250, 224));
    medicInputPanel.setBounds(12, 67, 349, 362);
    medicationsPanel.add(medicInputPanel);
    medicInputPanel.setLayout(new GridLayout(0, 2, 0, 10));
    
    JLabel lblID_1 = new JLabel("ID");
    medicInputPanel.add(lblID_1);
    
    medIDfield = new JTextField();
    medIDfield.setColumns(10);
    medicInputPanel.add(medIDfield);
    
    JLabel namelabel = new JLabel("Name");
    medicInputPanel.add(namelabel);
    
    medsNameField = new JTextField();
    medsNameField.setColumns(10);
    medicInputPanel.add(medsNameField);
    
    JLabel lblTime_1 = new JLabel("Dosage");
    medicInputPanel.add(lblTime_1);
    
    medsDoseField = new JTextField();
    medsDoseField.setColumns(10);
    medicInputPanel.add(medsDoseField);
    
    JButton btnaddMeds = new JButton("Add");
    btnaddMeds.setBackground(new Color(188, 108, 37));
    btnaddMeds.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        
        try {
          Database.addMedication(Integer.valueOf(medIDfield.getText()), medsNameField.getText(), medsDoseField.getText());
          Database.updateComboBox(medicationComboBox, "medication");
        } catch (NumberFormatException e1) {
          JOptionPane.showMessageDialog(medicInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);
          e1.printStackTrace();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
    });
    medicInputPanel.add(btnaddMeds);
    
    JButton btnRemoveMeds = new JButton("Remove");
    btnRemoveMeds.setBackground(new Color(188, 108, 37));
    btnRemoveMeds.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.delete(medIDfield.getText(),"medication");
          Database.updateComboBox(medicationComboBox, "medication");

        } catch (SQLException e1) {
          JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);

          e1.printStackTrace();
        }
        
      }
    });
    medicInputPanel.add(btnRemoveMeds);
    
    JScrollPane medScrollpane = new JScrollPane();
    medScrollpane.setBounds(364, 67, 419, 363);
    medicationsPanel.add(medScrollpane);
    
    medTable = new JTable();
    String[] medcolumn = {"ID","Name","Dosage"};
    DefaultTableModel medModel = new DefaultTableModel(medcolumn,0); 
    medTable.setModel(medModel);
    medScrollpane.setViewportView(medTable);
    
    JButton btnloadMedData = new JButton("Show All");
    btnloadMedData.setBackground(new Color(188, 108, 37));
    btnloadMedData.setBounds(376, 29, 100, 30);
    btnloadMedData.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.loadMedData(medModel);
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
        
      }
    });
    medicationsPanel.add(btnloadMedData);

    /*---------------------------------------------Patients Panel-----------------------------------------------------------------------*/
    JPanel patientsPanel = new JPanel();
    tabbedPane.addTab("Patients", null, patientsPanel, null);
    patientsPanel.setBackground(bgColor);
    patientsPanel.setLayout(null);
    
    JPanel patInputPanel = new JPanel();
    patInputPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 5), "Add Patient", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    patInputPanel.setBounds(12, 67, 349, 362);
    patInputPanel.setBackground(bgColor);
    patientsPanel.add(patInputPanel);
    patInputPanel.setLayout(new GridLayout(0, 2, 0, 10));
    
    JLabel lblName_1 = new JLabel("Name");
    patInputPanel.add(lblName_1);
    
    patientnameField = new JTextField();
    patInputPanel.add(patientnameField);
    patientnameField.setColumns(10);
    
    JLabel lblId_1 = new JLabel("ID");
    patInputPanel.add(lblId_1);
    
    patientIDfield = new JTextField();
    patInputPanel.add(patientIDfield);
    patientIDfield.setColumns(10);
    
    JLabel lblPhoneNo_1 = new JLabel("Phone No.");
    patInputPanel.add(lblPhoneNo_1);
    
    patientNumField = new JTextField();
    patInputPanel.add(patientNumField);
    patientNumField.setColumns(10);
    
    JLabel lblGender_1 = new JLabel("Gender");
    patInputPanel.add(lblGender_1);
    
    JComboBox<String> patientGenderComboBox = new JComboBox<String>();
    patientGenderComboBox.addItem("Male");
    patientGenderComboBox.addItem("Female");
    patientGenderComboBox.addItem("Other");
    patInputPanel.add(patientGenderComboBox);
    
    JLabel lblAge = new JLabel("Age");
    patInputPanel.add(lblAge);
    
    patientAgefield = new JTextField();
    patInputPanel.add(patientAgefield);
    patientAgefield.setColumns(10);
    
    JLabel lblAddress = new JLabel("Address");
    patInputPanel.add(lblAddress);
    
    patientAddressField = new JTextField();
    patInputPanel.add(patientAddressField);
    patientAddressField.setColumns(10);
    
    JButton btnaddPatient = new JButton("Add");
    patInputPanel.add(btnaddPatient);
    btnaddPatient.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.addPatient(Integer.valueOf(patientIDfield.getText()),
                    patientnameField.getText(),
                    patientGenderComboBox.getSelectedItem().toString(),
                    Integer.valueOf(patientAgefield.getText()),
                    patientAddressField.getText(),
                    patientNumField.getText()
                    );
          Database.updateComboBox(patientsComboBox, "patient");
          Database.updateComboBox(prescPatientsComboBox, "patient");
        } catch (NumberFormatException e1) {
          JOptionPane.showMessageDialog(patInputPanel, "Please enter an Valid ID/Age", "Invalid ID/Age", JOptionPane.ERROR_MESSAGE);
          e1.printStackTrace();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
        
      }
    });
    btnaddPatient.setBackground(new Color(188, 108, 37));
    
    JButton btnRemovePatient = new JButton("Remove");
    patInputPanel.add(btnRemovePatient);
    btnRemovePatient.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.delete(patientIDfield.getText(),"patient");
          Database.updateComboBox(patientsComboBox, "patient");
          Database.updateComboBox(prescPatientsComboBox, "patient");
        } catch (SQLException e1) {
          JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);
          e1.printStackTrace();
        }
        
      }
    });
    btnRemovePatient.setBackground(new Color(188, 108, 37));
    
    JScrollPane patScrollpane = new JScrollPane();
    patScrollpane.setBounds(364, 67, 419, 363);
    patientsPanel.add(patScrollpane);
    
    patTable = new JTable();
    String[] patColumns = {"ID","Name","Gender","Age","Address","Ph. Num"};
    DefaultTableModel patModel = new DefaultTableModel(patColumns,0);
    patTable.setModel(patModel);
    patScrollpane.setViewportView(patTable);
    
    JButton btnloadPatData = new JButton("Show All");
    btnloadPatData.setBackground(new Color(188, 108, 37));
    btnloadPatData.setBounds(376, 29, 100, 30);
    btnloadPatData.addActionListener(new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        try {
          Database.loadPatData(patModel);
        } catch (SQLException e1) {
          
          e1.printStackTrace();
        }
        
      }
    });
    patientsPanel.add(btnloadPatData);
    
    /*---------------------------------------------Doctors Panel-----------------------------------------------------------------------*/
        JPanel doctorsPanel = new JPanel();
        tabbedPane.addTab("Doctors", null, doctorsPanel, null);
        doctorsPanel.setLayout(null);
        doctorsPanel.setBackground(bgColor);
        
        JPanel docInputPanel = new JPanel();
        docInputPanel.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 5), "Add Doctor", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
        docInputPanel.setBackground(new Color(254, 250, 224));
        docInputPanel.setBounds(12, 67, 349, 362);
        doctorsPanel.add(docInputPanel);
        docInputPanel.setLayout(new GridLayout(0, 2, 0, 10));
        
        JLabel lblName_1_1 = new JLabel("Name");
        docInputPanel.add(lblName_1_1);
        
        docNameField = new JTextField();
        docNameField.setColumns(10);
        docInputPanel.add(docNameField);
        
        JLabel lblId_1_1 = new JLabel("ID");
        docInputPanel.add(lblId_1_1);
        
        docIDField = new JTextField();
        docIDField.setColumns(10);
        docInputPanel.add(docIDField);
        
        JLabel lblPhoneNo_1_1 = new JLabel("Phone No.");
        docInputPanel.add(lblPhoneNo_1_1);
        
        docNumField = new JTextField();
        docNumField.setColumns(10);
        docInputPanel.add(docNumField);
        
        JLabel lblGender_1_1 = new JLabel("Gender");
        docInputPanel.add(lblGender_1_1);
        
        JComboBox<String> docGenderComboBox = new JComboBox<String>();
        docGenderComboBox.addItem("Male");
        docGenderComboBox.addItem("Female");
        docGenderComboBox.addItem("Other");
        
        docInputPanel.add(docGenderComboBox);
        
        JLabel lblAddress_1 = new JLabel("Specialization");
        docInputPanel.add(lblAddress_1);
        
        docSpecialfield = new JTextField();
        docSpecialfield.setColumns(10);
        docInputPanel.add(docSpecialfield);
        
        JButton btnaddDoctor = new JButton("Add");
        btnaddDoctor.setBackground(new Color(188, 108, 37));
        btnaddDoctor.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.addDoctor(Integer.valueOf(docIDField.getText()),
                        docNameField.getText(),	
                        docGenderComboBox.getSelectedItem().toString(),
                        docSpecialfield.getText(), 
                        docNumField.getText() );
              Database.updateComboBox(docComboBox, "doctor");
              Database.updateComboBox(prescDocComboBox, "doctor");

            } catch (NumberFormatException e1) {
              JOptionPane.showMessageDialog(docInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);
              e1.printStackTrace();
            } catch (SQLException e1) {
              
              e1.printStackTrace();
            }
            
          }
        });
        docInputPanel.add(btnaddDoctor);
        
        JButton btnRemoveDoctor = new JButton("Remove");
        btnRemoveDoctor.setBackground(new Color(188, 108, 37));
        btnRemoveDoctor.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.delete(docIDField.getText(),"doctor");
              Database.updateComboBox(docComboBox, "doctor");
              Database.updateComboBox(prescDocComboBox, "doctor");
            } catch (SQLException e1) {
              JOptionPane.showMessageDialog(aptmtInputPanel, "Please enter an Valid ID", "Invalid ID", JOptionPane.ERROR_MESSAGE);
              e1.printStackTrace();
            }
            
          }
        });
        docInputPanel.add(btnRemoveDoctor);
        
        JScrollPane docScrollpane = new JScrollPane();
        docScrollpane.setBounds(364, 67, 419, 363);
        doctorsPanel.add(docScrollpane);
        
        docTable = new JTable();
        String[] docColumns = {"ID","Name","Gender","Specialization","Ph. Num"};
        DefaultTableModel docModel = new DefaultTableModel(docColumns,0);
        docTable.setModel(docModel);
        
        docScrollpane.setViewportView(docTable);
        
        JButton btnloadDocData = new JButton("Show All");
        btnloadDocData.setBackground(new Color(188, 108, 37));
        btnloadDocData.setBounds(376, 29, 100, 30);
        btnloadDocData.addActionListener(new ActionListener() {
          
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              Database.loadDocData(docModel);
            } catch (SQLException e1) {
              e1.printStackTrace();
            }
            
          }
        });
        doctorsPanel.add(btnloadDocData);
        
                
//				updating all the combo box with table values
          try { Database.updateComboBox(docComboBox, "doctor");
          Database.updateComboBox(patientsComboBox, "patient");
          Database.updateComboBox(prescDocComboBox, "doctor");
          Database.updateComboBox(prescPatientsComboBox, "patient");
          Database.updateComboBox(medicationComboBox, "medication"); }
          catch
          (SQLException e1) {
          
          e1.printStackTrace(); }
         
          
  }
}

Java Hospital Management System Output

hospital management system output

Summary

Congratulations! You have successfully completed this project on how to create a Hospital Management System using Java, Java Swing, SQLite, and Eclipse IDE.

By following this step-by-step guide, you now have a clear understanding of how to create a system to manage patient data, appointments, prescriptions, medications, doctors, and more. You have learned how to implement features such as input panels, tables, and database management.

You have learned how to use Java and Java Swing to create a user interface for your application. By utilizing various Swing components such as JTable, JPanel, JTabbedPane, and JButtons, you have created a clean and intuitive interface for managing hospital-related data.

You have also learned how to integrate SQLite database management into your application. You have learned how to create a database, establish a connection to it, and perform various database operations such as querying, inserting, updating, and deleting data.

By completing this project, you have also gained experience in using an Integrated Development Environment (IDE) such as Eclipse. You have learned how to use JAR files in Java projects, and you have gained a basic understanding of database management, including SQLite.

1 Response

  1. harish says:

    good

Leave a Reply

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