0% found this document useful (0 votes)
34 views80 pages

Priyanshu Kumar SinghReport

The document outlines a project report for a Hospital Management System developed by Priyanshu Kumar Singh as part of his Bachelor of Computer Application degree. It details the project's objectives, definitions, and the technology stack used, emphasizing the system's role in automating hospital operations to improve efficiency and patient care. The report includes acknowledgments, a certificate of originality, and a comprehensive index of the project's contents.

Uploaded by

Gamers Points
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views80 pages

Priyanshu Kumar SinghReport

The document outlines a project report for a Hospital Management System developed by Priyanshu Kumar Singh as part of his Bachelor of Computer Application degree. It details the project's objectives, definitions, and the technology stack used, emphasizing the system's role in automating hospital operations to improve efficiency and patient care. The report includes acknowledgments, a certificate of originality, and a comprehensive index of the project's contents.

Uploaded by

Gamers Points
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Institute of Management and Planning & Advanced Computer Training

(IMPACT), Patna

Affiliated to Aryabhatta Knowledge University

Project Report on
“Hospital Management System”
In Partial fulfilment for the award of the degree of

Bachelor of Computer Application (BCA)


(2022 - 2025)
By
Priyanshu Kumar Singh
(22303316003)
Under the guidance of
Mr. Devi Dayal Sinha
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to all those who have helped and

supported me in the successful completion of my final year project titled “Hospital

Management System”.

First and foremost, I extend my heartfelt thanks to Dr. Anurag Srivastava, my

project guide, for her valuable guidance, consistent encouragement, and

constructive suggestions throughout the development of this project. Her

mentorship has been a source of motivation and confidence for me.

I am also grateful to our respected Director, Mr. Manish Kumar, and Principal, Dr.

Niharika, for providing us with the opportunity, facilities, and academic environment

to carry out this project successfully as part of the curriculum.

I extend my sincere appreciation to the faculty members of the Department

of Computer Applications, my friends, and all those who directly or indirectly

contributed to the successful completion of this project.

Last but not least, I am thankful to my family for their moral support

and encouragement throughout the project duration.

This project has given me an opportunity to practically apply my academic

knowledge and enhance my skills in Java and database development, which will

be invaluable for my future career.

— Karina Kumari

Reg. No: 22303316039

Session: 2022–2025
CERTIFICATE
This is to certify that the project report entitled “Hospital Management System”

submitted by Ms. Karina Kumari (Registration No.: 22303316039), a student

of Bachelor of Computer Applications (BCA), Semester VI, Session

2022–2025,

has been carried out under my supervision in partial fulfilment of the requirements

for the degree of BCA from this institution.

This is a genuine and original work done by the student and has not been

submitted to any other university or institution for the award of any degree or

diploma.

The project work has been found satisfactory and is hereby approved.

………………………………………….. …………………………………………………
Signature of Guide Signature of Student

DECLARATION

I, Karina Kumari, bearing Registration No. 22303316039, a student of Bachelor of

Computer Applications (BCA), Semester VI, Session 2022–2025, hereby declare

that the project work entitled: “Hospital Management System”

submitted in partial fulfilment of the requirements for the degree of BCA is my

original work and has not been submitted previously by me or any other student to
any other university or institution for the award of any degree or diploma.

I further declare that all the information and data presented in this report have been

obtained and presented as per academic ethics and that any source used has been

duly acknowledged.

…………………………………………………………

Signature of the Student


INDEX

Sl. No. Topic Page No. 1. Introduction of the project 1 2. Objective of the project

2-3 3. Project definition 4-5 4. Project category 6-7 5. Tools & Platform 8-9 6.

Software & Hardware Requirements 10

7. Number of Modules 11-13 8. Data Structure 14-22 9. Input of the Project

23-25

10. Output of the Project 26-28 11. Data Flow Diagram 29-30 12. Security

Mechanism 31-32 13. Validation Checks 33-35 14. Coding & Implementation

36-153

15. System Testing 154-155 16. Feasibility Study 156-157 17. Future Scope

158-159 18. Conclusion 160

19. References 161

INTRODUCTION OF THE PROJECT


In today’s fast-paced world, the role of technology in streamlining and modernizing
various sectors has become more crucial than ever. Among the many domains
significantly impacted by digital transformation, the healthcare sector stands out.
Hospitals are no longer just places for medical treatment but have evolved into
complex organizations that require efficient administration, accurate data handling,
and timely communication among staff. Manual handling of records, appointments,
billing, and inventory is not only time-consuming but also leads to human error, data
loss, and inefficiency. To address these challenges, there is a growing need for a
centralized and automated Hospital Management System.

The proposed Hospital Management System (HMS) is designed to simplify the


day-to day operations of a hospital by providing a well-structured, role-based
software solution. It serves as an integrated platform that connects various
departments such as reception, doctor consultation, laboratory, and pharmacy. This
system reduces the paperwork burden and facilitates easy retrieval and storage of
patient data, medical history, and transaction records. It enables receptionists to
manage appointments, update patient information, and track billing seamlessly.
Doctors can access scheduled appointments, view patient details, and eventually
add diagnoses or prescriptions. Similarly, lab technicians will be able to upload and
manage test results, ensuring swift delivery of information to patients.

This system is built using Java (for GUI) and MySQL (for data storage), forming a
reliable and scalable architecture suitable for small to mid-sized hospitals or clinics.
The software provides secure login access to different users based on their roles,
and each module is designed to perform specific functions without overlapping
responsibilities. The overall goal is to create a simple, user-friendly, and efficient
hospital management environment that reduces operational delays and improves
service delivery to patients.

The development of this project is not just about building software it is about
transforming the way hospitals work internally, ensuring better healthcare outcomes
through improved administration. In the long run, such systems pave the way for
smart hospitals that can adapt to modern challenges and provide better care
through technology-driven solutions.

1
OBJECTIVE OF THE PROJECT
The primary objective of this project, Hospital Management System, is to design and
implement a fully functional software solution that effectively manages all the critical
operations of a hospital in a structured, reliable, and efficient manner. This project
aims to reduce the burden of manual administrative work, ensure data integrity, and
provide a user-friendly interface for hospital staff across all departments. By
introducing automation and digital workflows, the system helps bridge the gap
between technology and healthcare services, ensuring that both patients and
hospital staff benefit from accurate, timely, and accessible information.

This system is intended to simplify the complex, interdependent tasks performed in


a hospital, such as patient registration, appointment scheduling, lab test recording,
inventory tracking, billing, and prescription management. It introduces a modular
and scalable architecture that allows each department to work independently while
being connected to a centralized database. Every module is tailored to a specific
user type, such as receptionists, doctors, lab technicians, pharmacists, and
administrators, ensuring role-based access and operational control.

A major focus of the project is data accuracy and consistency. In manual systems,
duplication and errors in patient records, medication details, or billing are common.
Through digitization, the system ensures that data entered once is reused across
relevant modules, minimizing mistakes and delays. It also supports historical data
tracking, which allows doctors and staff to refer to previous treatments, test results,
and prescriptions, thereby improving diagnosis and decision-making.

Another important objective is process automation. Instead of relying on verbal


communication or physical files being moved from one department to another, the
system instantly reflects updates such as a confirmed appointment, a lab report
upload, or a paid bill. This leads to faster service delivery, better patient experience,
and less administrative overhead.

The system also supports inventory automation, where medicines and consumables
are tracked in real-time. Whenever a doctor prescribes a medicine or a test is
conducted, the corresponding items are automatically deducted from the inventory.
Alerts for low

2
stock levels help hospital administrators reorder supplies on time, avoiding
out-of-stock situations.

Security and access control are also essential objectives. The system enforces
login based authentication, and users are restricted to the modules and actions
relevant to their role. For example, doctors cannot alter billing data, and
receptionists cannot edit medical diagnoses. This not only ensures data safety but
also maintains accountability.

Additional objectives include:

 Reducing waiting time for patients through better appointment management


and faster billing.

 Minimizing paper records, which are hard to maintain and retrieve.

 Improving patient care quality through accurate medical history access and
faster lab reporting.

 Enhancing transparency by keeping a traceable record of all activities such


as treatments, lab tests, and inventory usage.

 Providing scalability, so the hospital can add more users or modules in the
future without reworking the entire system.

Ultimately, the goal is to modernize the hospital’s functioning by offering a powerful


yet easy-to-use system that ensures operational excellence, enhances patient
satisfaction, and sets the foundation for further digital transformation in the
healthcare sector.

3
PROJECT DEFINITION
The Hospital Management System (HMS) is a comprehensive, modular software
application designed to automate the core operations and workflow of a hospital or
medical facility. It provides a unified platform that integrates different departments
such as patient registration, appointments, doctor consultations, billing, inventory,
laboratory management, and report handling under one centralized system.

This project is defined as a role-based, multi-user desktop application that allows


hospital staff and administrators to manage day-to-day hospital activities efficiently.
The system offers tailored access to each user type—such as Receptionist, Doctor,
Lab Technician, and Administrator—by providing them with only the relevant features
needed for their responsibilities. Each operation, from admitting a new patient to
issuing a final bill, is carried out digitally, reducing manual errors and enhancing
speed and coordination between departments.

Key Highlights of the Project Definition:

 Patient-Centric Design: The system maintains a complete profile for each


patient, including demographic information, medical history, illness details,
prescriptions, test results, and payment records. This helps doctors and staff
to access all required data in one place and make informed decisions.

 Modular Architecture: Every major operation is developed as an independent


module (e.g., Manage Patients, Manage Appointments, Manage Billing,
Manage Inventory, Lab Reports), yet they are all connected through a
centralized database. This modular design ensures scalability and ease of
maintenance.

 Real-Time Data Management: The system allows for instant updates. For
example, once a patient is registered, the receptionist can immediately
schedule appointments. Once a doctor prescribes medicines or lab tests,
the inventory is updated and a lab report is initiated. This eliminates
unnecessary delays and miscommunication.

 Automated Inventory: The system tracks all medical supplies, drugs, and
consumables. It automatically reduces inventory quantities when a
prescription

4
is issued or a test is conducted. This ensures accurate stock levels,
helps in procurement planning, and avoids shortage crises.

 Appointment Handling: Appointments can be scheduled both internally by


reception and externally by patients (if enabled). The system supports status
tracking—pending, confirmed, cancelled, or completed—and helps avoid
double booking or conflicts in a doctor’s schedule.

 Billing & Payment Processing: The billing module calculates total charges,
maintains the status of each bill (unpaid or paid), and records the payment
mode. It also links with appointments to ensure that bills are generated only
after consultations or lab services are completed.

 Security and Role-Based Access Control: Each user must log in using secure
credentials. The system restricts access according to roles. For instance, a
receptionist can’t access or edit doctor’s diagnoses, and a lab technician
cannot view financial reports.

 User Interface and Usability: The software has been designed using Java
Swing with a clean, modern UI. All forms and tables follow a consistent color
palette and intuitive layouts to make the system easy to learn and use, even
by non technical staff.

In essence, the Hospital Management System project defines a complete digital


workflow for hospitals that minimizes paperwork, streamlines tasks, and improves
operational efficiency while ensuring accuracy and transparency in patient care
and hospital management.

5
PROJECT CATEGORY
The Hospital Management System falls under the category of Application Software
in the domain of Healthcare Information Systems (HIS). It is specifically designed
as a Java-based Desktop Application with a backend powered by MySQL for data
storage and management.

Explanation of the Project Category:

1. Application Software
The system is a real-time, interactive application intended for use by
hospital staff, doctors, and administrators. It performs specific tasks such
as patient registration, appointment scheduling, billing, inventory control,
and lab report management. As application software, it runs on end-user
machines and is developed with a user-friendly interface to simplify
hospital workflow.

2. Healthcare Information System (HIS)


This project contributes to the automation of healthcare processes by storing
and managing patient-related data and administrative tasks. It is a practical
implementation of HIS, aiming to reduce manual errors, improve data
accessibility, and increase the quality of patient care.

3. Role-Based Access System


It belongs to the category of Multi-User Role-Based Systems, where each
user (e.g., receptionist, doctor, lab technician, admin) has a specific set of
permissions. The software restricts access to sensitive data and operations
based on user roles, thus enhancing security and compliance.

4. Standalone Desktop Application


The software is built as a Java Swing-based desktop application, making it
suitable for local deployment within hospital premises without the need for
internet access. This ensures faster performance, enhanced security, and
offline availability. However, it can later be upgraded to a web-based or
cloud-based system if required.

5. Database-Driven System
It is a Relational Database Management System (RDBMS) powered
6
application, using MySQL as the backend. This allows efficient storage,
retrieval, and manipulation of structured data, such as patient records,
appointments, billing transactions, inventory items, and test reports.

6. Modular and Scalable


The project is categorized as a Modular Software System, meaning it consists
of independent but interlinked modules such as "Manage Patients", "Manage
Appointments", "Manage Doctors", "Billing", "Inventory", and "Lab Reports".
This approach allows the software to be easily extended or modified in the
future, such as adding new modules like "Discharge Summary", "Insurance
Claims", or "Emergency Ward Tracking".

7. Educational Project with Real-World Application


This project is also classified under Academic Major Projects for BCA
students, but it is built with a real-world hospital environment in mind. The
concepts used in this project closely resemble commercial hospital software,
making it valuable for both learning and demonstration purposes.
7
TOOLS & PLATFORM
The Hospital Management System (HMS) project uses a combination of tools
and technologies that are easy to work with, reliable, and suitable for
desktop-based applications. Below is a categorized list of tools and platforms
used:

Frontend (User Interface)

 Language: Java (Swing)

 Toolkit: javax.swing

 Theme/Design: FlatLaf (for modern look and feel)

 Features: Custom UI panels, tables, forms, dialog boxes

Backend (Logic & Application)

 Language: Java
 Version: Java 21 (LTS)

 IDE Used: Apache NetBeans 18

 Features: Event-driven logic, validations, data processing, file

I/O Database

 Database System: MySQL 8.3 (Community Edition)

 Tool Used: MySQL Workbench

 Connection: JDBC (Java Database Connectivity)

 Usage: Storing patient data, appointments, lab reports, inventory, users,


login info

Build & Project Management

 Tool: Apache Maven

 Purpose: Manage dependencies, build project, generate JAR files

8
Version Control

 Tool: Git

 Hosting: GitHub

 Usage: Track code changes, collaborate with team

Testing Tools (Basic Level)

 Tool: JUnit

 Purpose: Test core functions and data operations

Documentation

 Tool: Microsoft Word 365

 Diagrams: Draw.io (for ER diagram, flowcharts, DFD,


etc.) Operating Environment

 OS: Windows 11 (Recommended)

 Requirements: Java JDK, MySQL Server, NetBeans IDE

This setup is suitable for offline desktop use in hospitals or clinics and is
beginner friendly for students working on Java + MySQL projects.

9
SOFTWARE & HARDWARE REQUIREMENTS
To run and develop the Hospital Management System (HMS) smoothly, the
following hardware and software setup is required:

Hardware Requirements:

A computer or laptop with at least Intel Core i3 processor or equivalent

 Minimum 4 GB RAM (8 GB recommended for better performance) 

Around 200 MB free disk space for project files and database  Standard

keyboard and mouse for input

 Display resolution of 1366×768 or higher

 Battery backup or UPS is recommended in clinics to avoid data


loss Software Requirements:

 Operating System: Windows 10 or 11 (64-bit preferred)

 Java Development Kit (JDK): Java 21 (LTS version)

 IDE (Editor): Apache NetBeans 18 for writing and designing the application

 Database: MySQL 8.3 (Community Edition) for data storage

 Connector: MySQL JDBC driver (Connector/J) for Java–MySQL

communication  Word Processor: Microsoft Word 365 or LibreOffice Writer for

documentation  Diagram Tool: Draw.io or Diagrams.net (for ERD, flowcharts,

DFDs)

 PDF Reader: Adobe Acrobat Reader (for viewing reports, if PDF generation
is added later)

 Browser: Chrome or Firefox (for downloading tools, libraries, and resources)

 This configuration is easy to arrange in most college labs or clinics and


supports both development and real-time use.

10

NUMBER OF MODULES
The Hospital Management System is designed with multiple modules to handle
different tasks in a hospital. Each module has a specific purpose and works together
with others to manage hospital operations effectively. Below is the logic and purpose
of each module:

1. Login Module

 Allows only registered users (Admin, Receptionist, Doctor, Lab Assistant, etc.)
to log in.

 Verifies username and password from the database.

 Uses role-based redirection — each user is taken to their respective


dashboard after login.

 Basic input validation is applied for security.

2. Admin Dashboard

 Accessible only by the admin after successful login.

 Controls the entire system — add/edit/delete users, doctors, lab staff,


and receptionists.

 Can view reports of patients, appointments, lab results, and

inventory.  Provides links to every module and logout feature.

3. Manage Patients Module

 Used by receptionists to add new patients with their personal and


medical details.

 Allows updating or deleting existing patient records.

 Stores patient info like name, age, gender, contact, address, and
admission reason.

 Each patient gets a unique ID for tracking.

4. Appointment Module

11
 Allows reception to schedule appointments with doctors.

 Shows available doctors and time slots.

 Stores appointment details like patient ID, doctor ID, date, and

time.  Avoids duplicate or overlapping appointments.

5. Doctor Dashboard Module

 Doctors can view their appointments for the day.

 Can access full patient history and write diagnosis or

prescription.  Allows updating patient’s treatment record.

 Option to view lab reports or refer patient to lab if needed.


6. Laboratory Module (Lab Reports)

 Used by lab assistant to upload test results of patients.

 Reports are linked with patient ID and test type.

 Doctors and admin can view these reports.

 Allows updating or removing reports when required.

7. Inventory Management Module

 Tracks medicines, surgical supplies, and lab items.

 Admin can add new stock or update quantity.

 Auto-decrease logic (planned) when medicines are prescribed by

doctors.  Warns when stock is below minimum level.

8. Appointment Approval Panel

 Admin or doctors can approve or reject appointment requests.

 Only approved appointments are sent to the doctor's

dashboard.  Ensures proper handling of doctor’s schedule.

9. Billing Module (Optional/Future Scope)

12
 Generates bill based on patient treatments, tests, and

medications.  Calculates total charges and applies taxes or

discounts.

 Can export bill as PDF or print (to be added later).

10. Logout Feature:

 Available in every dashboard and module.

 Ends the user session securely and returns to the login

screen.  Prevents unauthorized access after logout.

Each module is built using Java Swing for frontend, and all data operations are
handled using MySQL queries via JDBC.

13

DATA STRUCTURE
The Hospital Management System uses structured relational database tables in
MySQL to store and manage all institutional data securely and efficiently. Each table
is linked using primary and foreign keys to maintain data integrity. Temporary
processing within the Java application uses in-memory structures like Array, List,
HashMap, and StringBuilder.

MAIN DATABASE

Schema Overview:
 Receptionist → Appointment Receptionists can book appointments on behalf
of patients.

 Doctor ↔ Appointment ↔ Patient An appointment links one patient with one


doctor at a specific date and time.

 Prescription ↔ Appointment Every prescription is issued during an


appointment.

 Prescription ↔ Prescription_Medicine ↔ Inventory Medicines prescribed are


drawn from the inventory table; quantities are tracked.

 Lab_Report → Patient (↔ Doctor optional) Lab reports belong to patients; a


doctor reference is optional.

 Bill → Patient & Appointment Bills consolidate charges for a patient’s


appointment and chosen payment mode.

Detailed Table Definitions:

 PK = Primary Key
 FK = Foreign Key
 NN = NOT NULL
 UQ = UNIQUE
 DEF = Default

14
1. RECEPTIONIST TABLE:

Column Data Type Constraints Description


receptionist_id INT PK, Unique receptionist number
AUTO_INCREMENT
name VARCHAR (100) NOT NULL Full Name
email VARCHAR (100) NOT NULL, Login/ Contact Email
UNIQUE
phone VARCHAR (15) - Mobile Number
password VARCHAR (100) NOT NULL Encrypted
Password
2. DOCTOR TABLE:

Column Data Type Constraints Description


doctor_id INT PK, AUTO Unique doctor number
INCREMENT
name VARCHAR (100) NOT NULL Full Name

specialization VARCHAR (100) - Medical Field (Eg. Cardiology)


phone VARCHAR (15) - Contact Number
email VARCHAR (100) NOT NULL, Professional Email
UNIQUE

password VARCHAR (100) NOT NULL Encrypted


Password

15
3. PATIENT TABLE:

Column Data Type Constraints Description


patient_id INT PK, AUTO Unique patient number
INCREMENT
name VARCHAR (100) NOT NULL Full Name age INT - Age in years

gender VARCHAR (10) - Gender email VARCHAR (100) UNIQUE Contact

email phone VARCHAR (15) - Contact Number

illness TEXT - Illness or symptoms

password VARCHAR (100) NOT NULL Encrypted


passworrd

4. APPOINTMENT TABLE;

Column Data Type Constraints Description


patient_id INT NOT NULL, FK->patient INCREMENT
doctor_id INT NOT NULL, FK->doctor Patient

appointment_id INT PK, AUTO


Doctor
appointment id
Unique
appointment_date DATE NOT NULL Date appointment_time TIME NOT NULL

Time status ENUM Default ‘pending’ Appointment status

booked_by ENUM NOT NULL Booked by

16
5. PRESCRIPTION TABLE:

Column Data Type Constraints Description


prescription_id INT PK, AUTO Unique
INCREMENT prescription Number
Appointment Doctor
apoointment_id INT NOT NULL,
FK->appointment
Patient
doctor_id INT NOT NULL, FK->doctor
patient INT NOT NULL, FK->patient

notes TEXT - Clinical Notes medicine TEXT - Medicine List

date DATE NOT NULL Prescription Date

6. PRESCRIPTION MEDICINE TABLE:

Column Data Type Constraints Description


prescription_id INT NOT NULL, FK->inventory
FK->prescription Prescription Medicine

medicine_id INT NOT NULL,

quantity INT NOT NULL Units prescribed


unit_price DECIMAL (10,2) NOT NULL Price per unit

7.LAB REPORT TABLE:

Column Data Type Constraints Description


patient_id INT NOT NULL, >doctor
FK->patient Patient Doctor

doctor_id INT NOT NULL,FK-

report_text TEXT - Findings


date DATE NOT NULL Report date

17
8. INVENTORY TABLE:

Column Data Type Constraints Description


medicine_id INT PK, AUTO Unique medicine number
INCREMENT
name VARCHAR (100) NOT NULL Medicine/ Supply name
quantity INT NOT NULL DEFAULT 0 Quantity in stock

price_per_unit DECIMAL NOT NULL Price per unit


DEFAULT 0.00

9. BILL TABLE :

Column Data Type Constraints Description


patient_id INT NOT NULL, FK->patient Patient
appointment_id INT NOT NULL,
FK->appointment Appointment Total bill amount

total_amount DECIMAL (10,2) NOT


NULL, DEFAULT 0.00

status ENUM Default ‘unpaid’ Bill status


payment_mode ENEM - Payment method

Design Notes

1. Normalization & Integrity

o Every table has a single, numeric surrogate PK to keep joins efficient.

o Foreign-key constraints use ON UPDATE CASCADE to keep


references in sync; deletions cascade only where business rules
allow (e.g., removing a patient deletes their appointments).

18
2. Security

o Passwords are stored as encrypted hashes, never plaintext.

o Role-based access is enforced at the application layer (e.g., only


doctors can write prescriptions).

3. Scalability

o Separating prescription_medicine from prescription supports


many-to-many relations between prescriptions and stocked medicines.

o Nullable doctor_id in lab_report allows reception-initiated tests when a


doctor isn’t involved.

4. Extensibility

o New payment modes, appointment statuses, or inventory categories


can be added by altering ENUM lists—no structural overhaul required.

o Additional modules (e.g., radiology images, ambulance scheduling)


can link cleanly via patient or appointment IDs.

JAVA DATABASE

In the Hospital Management System, Java is used as the primary programming


language to build the desktop application. To manage and process the data
efficiently within the application (in memory), various Java Collection Framework
(JCF) and basic data structure concepts are used. These data structures help
manage patient information, appointments, prescriptions, and inventory before
syncing with the MySQL database.

The key Java data structures used in this project are described

below: 1. ArrayList

 Used to store lists of data like patients, doctors, lab reports, and
appointments temporarily.

 Allows dynamic resizing and fast access using indexes.

 Ideal for displaying data in tables (like JTable components in Swing).


19
 Example use:

o ArrayList<Patient> patientList

o ArrayList<Appointment> appointments

2. HashMap

 Used to store key-value pairs such as:

o Doctor IDs mapped to doctor objects.

o Medicine names mapped to quantity or prices.

 Provides constant time complexity for search, insert, and update

operations.  Example use:

o HashMap<Integer, Doctor> doctorMap

o HashMap<String, Integer> inventoryMap

3. HashSet

 Used to ensure no duplicates exist in lists such as available


departments, existing emails, or scheduled appointment times.

 Example use:

o HashSet<String> departmentSet

o HashSet<String> bookedSlots

4. Queue (LinkedList implementation)

 Can be used to handle appointment queues or billing orders in first-in-first-out


(FIFO) order.

 Though not required in all modules, it’s useful for future extensions like
patient waitlists or token systems.

 Example:
o Queue<Appointment> waitingQueue = new LinkedList<>();

20
5. Custom Classes (POJOs)

To represent each module’s entity (like patients, doctors, lab reports), Plain Old
Java Objects (POJOs) were created. These act like local data structures to:

 Hold form data before saving to the database.

 Retrieve rows from SQL queries into objects.

 Pass data between UI and logic layers.

Example POJO Classes:

 Patient.java

 Doctor.java

 Appointment.java

 Prescription.java

 LabReport.java

 InventoryItem.java

Each of these classes contains:

 Attributes (e.g., name, age, gender)

 Getters and Setters

 Constructors

 ToString() (for debugging/logs)

6. 2D Arrays (Optional/Legacy)

 Sometimes used to pass data directly into table models (e.g.,


Object[][] tableData).

 Useful for quick visualization in GUIs but replaced by more modern


TableModel techniques.
21
7. Model-View-Controller (MVC) Pattern

While not a data structure itself, the MVC pattern organizes Java code

into:  Model: Java classes and data structures (e.g., Patient.java)

 View: Swing forms and GUI components

 Controller: Java logic that processes actions and connects models to views

This architecture indirectly improves data structure clarity and usage across the
application.
22
INPUT OF THE PROJECT
Every software system relies on accurate and properly structured inputs to
function correctly. In the Hospital Management System, inputs are taken from
users such as receptionists, doctors, lab assistants, and patients, and are used to
process, store, and retrieve healthcare data effectively.

The input process has been carefully designed to ensure validity, reliability, and
security. All input forms are user-friendly and equipped with validations to reduce
data entry errors.
Below are the major inputs of this project categorized

module-wise: 1. Receptionist Input

 New Patient Registration

o Name, Age, Gender

o Contact Number, Email (optional)

o Address and Illness Details

o Password (for patient login)

 Appointment Booking

o Patient Name or ID (selection)

o Doctor Name or ID

o Appointment Date and Time

o Booking Type: Patient or Receptionist

2. Doctor Input

 Prescription Entry

o Medicines prescribed

o Dosage, Frequency, Duration

o Medical Notes

23
o Date of prescription

 Patient Assessment

o Viewing patient history

o Adding remarks to appointments

o Referring patients for lab tests

3. Lab Assistant Input

 Lab Report Upload


o Selecting Patient and Test Type

o Report Text or Summary

o Upload Date

o Optionally assigning referring Doctor

4. Inventory Input (Admin or Staff)

 Inventory Management

o Medicine or Item Name

o Quantity in Stock

o Price Per Unit

o Updating item when used or added

5. Billing Input

 Bill Generation

o Patient and Appointment ID

o Total Amount

o Status (Paid or Unpaid)

o Payment Mode: Cash / Card / UPI

24
6. Login and Access Input

 Username and Password

o Receptionist, Doctor, and Patient must provide correct credentials to


log in.

o Each role is directed to their respective dashboard after validation.

Input Validations and Checks

To maintain accuracy and prevent invalid entries, the following checks are
enforced:  Mandatory fields (e.g., Name, Phone, Password)

 Proper date/time format for appointments and lab reports

 Unique entries for emails and IDs

 Dropdown lists for role, gender, status, etc.

 Password masking and length validation

25

OUTPUT OF THE PROJECT


The primary goal of the Hospital Management System is to deliver accurate,
real-time, and organized output based on the inputs given by various users. The
system provides a wide range of outputs that assist in clinical decisions, patient
management, administrative workflow, and inventory tracking.

Each output is designed to be user-friendly, easy to interpret, and structured in a


format suitable for display, printing, or future reference.

Below is a module-wise breakdown of the system outputs:


1. Patient Module Output

 Patient Profile View

o Displays registered patient details: Name, Age, Gender, Contact

Info.  Appointment History

o List of all appointments taken by the patient.

 Prescriptions and Reports

o View of all prescriptions and uploaded lab reports associated with the
patient.

2. Doctor Module Output

 Daily Appointment List

o Shows the doctor’s appointments scheduled for the current

day.  Patient Case Details

o Retrieves patient's illness history and previous prescriptions.

 Prescription Summary

o Displays a list of medicines and instructions issued to patients.

26
3. Receptionist Module Output

 New Registrations Confirmation

o Shows confirmation message and unique patient ID after


successful registration.

 Appointment Booking Result

o Displays appointment number, patient name, doctor name, date and

time.  Success/Failure Messages


o Notifies the receptionist if booking, update, or deletion was

successful. 4. Lab Report Output

 Lab Report View

o Patient-wise listing of lab results with date and doctor (if referred).

 Detailed Report Content

o Shows result summary, values, remarks, and attached documents


if available.

5. Inventory Output

 Available Stock Report

o Displays a list of all medicines/supplies with quantity and price.

 Low Stock Alert

o Highlights items falling below threshold stock levels.

 Medicine Usage Summary

o Output based on prescribed and issued quantities per day/week.

6. Billing Output

 Generated Bill Details

o Patient name, appointment details, service costs, medicine

charges.  Total Payable Amount

27
o Shows final payable after any tax or discount (if applicable).

 Payment Status

o Paid or unpaid status and mode of payment.

7. Login & Access Output

 Dashboard Redirection

o Based on role (doctor, receptionist, patient), redirects to respective


panel.  Login Feedback

o Success or error messages during login with proper prompts.

Format of Output Presentation

All outputs are displayed using:

 Java Swing UI components (like JTable, JLabel, JTextArea)

 Printable panels or export-ready views (PDF export can be added in future)

 Color-coded status indicators (e.g., confirmed appointments in green,


unpaid bills in red)

28

DATA FLOW
DIAGRAM

LEVEL 0 DFD:

RECEPTIONIST
PATIENT

DOCTOR HOSPITAL

LEVEL 1 DFD:
MANAGEMNT SYSTEM

29
LEVEL 2 DFD:
30

SECURITY MECHANISM
Security is a critical aspect of any software system, especially in a hospital
environment where sensitive patient data, confidential medical records, and financial
transactions are involved. The Hospital Management System has been developed
with a focus on ensuring data protection, role-based access, and secure operations
across all modules.
The following mechanisms have been implemented to protect the system
from unauthorized access, data breaches, and misuse.
1. Authentication System
The system ensures that only registered users can access their respective
panels:  Username and Password login system for:

o Receptionist

o Doctor

o Patient

 Logincredentials are validated at the database level using encrypted or hashed


passwords (can be added using SHA or bcrypt in future).

 Incorrect login attempts are blocked with error messages to prevent brute-force
attacks.
2. Role-Based Access Control (RBAC)
Each user has access only to the features relevant to their role:
 Receptionist:

o Can register patients, book appointments, generate bills.


o Cannot view prescriptions or lab reports.
 Doctor:

o Can view their appointments, prescribe medicines, and upload


lab reports.
o Cannot modify billing or register patients.
 Patient:

o Can only view their own appointments, prescriptions, lab results, and bill
status.
This structure prevents unauthorized access and ensures data privacy.
3. Input Validation

To prevent injection attacks and malformed data entry:

31
 All input fields (registration, appointments, reports) are validated using:
o Character limit checks

o Email and phone format validation


o Date and time format enforcement
 This reduces the risk of SQL injection, XSS, and other common
attacks. 4. Secure Database Transactions

 All database interactions are handled using PreparedStatements via JDBC.

 This prevents SQL injection vulnerabilities, ensuring that user input cannot
directly manipulate database queries.
5. Password Protection
 Although currently stored as plain text for demo purposes, the system is
designed to support hashed password storage using algorithms like
SHA-256 or bcrypt.
 This ensures that even if the database is compromised, user passwords
remain unreadable.
6. Session Control and Logout

 Each user is assigned a session after login and redirected to their


respective dashboard.
A Logout option is provided for all roles to prevent session misuse. 
Inactive users can be manually logged out or timed out in future updates.
7. User Data Integrity

 System ensures that one user’s data cannot be modified or viewed by


another:
o Patients can only see their own data.
o Doctors can only access information related to their appointments.
 Deleting patient records will automatically cascade and remove related
reports and bills to avoid data inconsistency.
8. Administrative Controls (Future Scope)
 The system is designed to support admin dashboards for advanced monitoring.

 Role creation, permission updates, and audit logs can be added to


enhance security further.

32
VALIDATION CHECKS
Validation checks are essential to ensure that the input data collected through the
application is accurate, reliable, and secure. In the Hospital Management System,
multiple validation mechanisms have been implemented at the user interface level
and the backend level to prevent invalid, incomplete, or malicious data from entering
the system.
Proper validation improves data quality, enhances user experience, and
helps prevent system crashes or security vulnerabilities.
1. Text Field Validations
 Name Fields (Patient, Doctor, Receptionist):
o Must not be empty.
o Accepts only alphabets and spaces.
o Minimum 2 characters and maximum 100 characters.
 Email Address:
o Must follow standard format (e.g., user@example.com).
o Must be unique across the database.
o Checked using regular expression (regex) pattern.
 Phone Number:
o Must contain only digits.
o Length must be 10 digits.
o Cannot contain alphabets or special characters.
2. Numeric Field Validations
 Age (in Patient Registration):
o Must be a valid integer between 0 and 120.
o Cannot be empty or contain letters.
 Medicine Quantity & Unit Price (Inventory):
o Quantity must be a non-negative integer.
o Unit price must be a positive decimal (e.g., 10.50).
 Billing Amounts:
o Checked to ensure non-zero, positive values only.
o Total must reflect correct calculation from services and medicines.

33
3. Password Field Validations
 Password must not be empty.
 Minimum length of 6 characters.
 Can include alphabets, digits, and special characters.
 Input is masked (shown as asterisks) for security.
4. Date and Time Validations
 Appointment Date:
o Cannot be in the past.
o Must be a valid calendar date (e.g., no Feb 30).
 Appointment Time:
o Must follow the proper format (HH:MM).
o Checked against doctor’s availability.
 Prescription and Lab Report Dates:
o Cannot be future dates.
o Must match the format YYYY-MM-DD.
5. Drop-down and Enum Validations
 Gender Selection:
o Only options: Male, Female, Other
o Cannot leave unselected.
 Status Fields (e.g., Billing Status, Appointment Status):
o Mustbe chosen from predefined values (e.g., Paid, Unpaid,
Confirmed, Cancelled).
 Payment Mode:

o Must be selected from: Cash, Card, or UPI.


o Prevents wrong data entry and improves report accuracy.
6. Duplicate Entry Prevention
 Email addresses for patients, doctors, and receptionists must be unique. 
Appointments cannot be double-booked (same patient, doctor, and time slot).
 Inventory items must have unique medicine names.

7. Mandatory Fields

34
All critical fields are marked as required. The form does not proceed
unless:  All required fields are filled

 All formats are valid


 All dropdowns are selected properly
An error dialog or message is shown if validation fails.
35

SYSTEM IMPLEMENTATION
System implementation is the stage where the developed and tested software is
deployed and made operational in a real-world environment. It involves converting
theoretical designs and code into a working solution that users can interact with. For
the Hospital Management System, the implementation phase focused on seamless
installation, user accessibility, and real-time interaction with the database and GUI
modules.
DATABASE CONNECTION
package hospital.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static final String URL = "jdbc:mysql://localhost:3306/hospital_db";
private static final String USER = "root";

private static final String PASSWORD = "7070";


private DBConnection() {}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER,
PASSWORD); }

LOGIN PAGE

36
CODE
package hospital.ui.login;
import hospital.database.DBConnection;
import hospital.ui.doctor.DoctorContext;
import hospital.ui.doctor.DoctorDashboard;
import hospital.ui.patient.PatientDashboard;
import hospital.ui.receptionist.ReceptionistDashboard;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
/**
* Modernised login window (pure Swing, no external libs).
*/
public class LoginFrame extends JFrame {
/* ------------- THEME ------------- */
private static final Color BG_COLOR = new Color(0xF4F7FA);
private static final Color CARD_COLOR = Color.WHITE;

private static final Color PRIMARY_COLOR = new Color(0x1976D2); // blue


private static final Color PRIMARY_HOVER = new Color(0x1565C0); private
static final Color ACCENT_COLOR = new Color(0x455A64); private static final
Font FONT_HEADER = new Font("SansSerif", Font.BOLD, 22); private static
final Font FONT_SUB = new Font("SansSerif", Font.PLAIN, 14);

/* ------------- FIELDS ------------- */


private final JComboBox<String> comboRole = new JComboBox<>(new
String[]{ "Doctor", "Receptionist", "Patient"

37
});
private final JTextField txtEmail = new JTextField(25); private
final JPasswordField txtPass = new JPasswordField(25);
public LoginFrame() {
setTitle("Hospital Management – Login");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(BG_COLOR);
setResizable(false);
buildUI();
pack();
setLocationRelativeTo(null);
}
/* ------------- BUILD UI ------------- */
private void buildUI() {
/* outer background */
JPanel root = new JPanel(new GridBagLayout());
root.setBackground(BG_COLOR);
add(root);
/* inner card */
JPanel card = new JPanel();
card.setBorder(new MatteBorder(1,1,4,4,new Color(0xDDE3EB)));
card.setBackground(CARD_COLOR);

card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));


card.setPreferredSize(new Dimension(380, 340));
root.add(card);

/* heading */
JLabel lblTitle = new JLabel("Welcome Back");
lblTitle.setFont(FONT_HEADER);
lblTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
lblTitle.setBorder(new EmptyBorder(15,0,5,0));

38
JLabel lblSub = new JLabel("Login to continue");
lblSub.setFont(FONT_SUB);
lblSub.setForeground(ACCENT_COLOR);
lblSub.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(lblTitle);

card.add(lblSub);
card.add(Box.createRigidArea(new Dimension(0, 15)));
/* form panel */
JPanel form = new JPanel();
form.setOpaque(false);
form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS));
card.add(form);

form.add(field("Role", comboRole));
form.add(field("Email", txtEmail));
form.add(field("Password", txtPass));
/* buttons */
JButton btnLogin = primaryButton("Login");
JButton btnReg = textButton("New Patient Registration");
JButton btnForgot = textButton("Forgot Password");

btnLogin .addActionListener(e -> doLogin());


btnReg .addActionListener(e ->
new hospital.ui.patient.PatientRegistrationFrame(this).setVisible(true));
btnForgot.addActionListener(e ->

new ForgotPasswordDialog(this).setVisible(true));
card.add(Box.createVerticalStrut(10));
btnLogin.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(btnLogin);

card.add(Box.createVerticalStrut(10));
JPanel linkRow = new JPanel();
linkRow.setOpaque(false);

39
linkRow.add(btnReg);
linkRow.add(Box.createHorizontalStrut(10));
linkRow.add(btnForgot);
card.add(linkRow);
card.add(Box.createVerticalGlue());
}
/* helper to build a labelled field row */
private JPanel field(String label, JComponent comp) {
JLabel lbl = new JLabel(label);
lbl.setPreferredSize(new Dimension(80, 28));
lbl.setFont(FONT_SUB);

comp.setMaximumSize(comp.getPreferredSize());

comp.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 4));
row.setOpaque(false);

row.add(lbl);
row.add(comp);
return row;
}
/* UI helpers for buttons */
private JButton primaryButton(String text) {
JButton b = new JButton(text);
b.setForeground(Color.WHITE);
b.setBackground(PRIMARY_COLOR);
b.setFocusPainted(false);

b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b.setPreferredSize(new Dimension(160, 35));

b.addMouseListener(new Hover(b, PRIMARY_COLOR,


PRIMARY_HOVER)); return b;

40
}
private JButton textButton(String text) {
JButton b = new JButton(text);
b.setForeground(PRIMARY_COLOR);
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setFocusPainted(false);

b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b.setFont(FONT_SUB);

b.addMouseListener(new Hover(b, null, null));


return b;
}
private static class Hover extends MouseAdapter {
private final JButton btn;
private final Color base, hover;
Hover(JButton btn, Color base, Color hover) {
this.btn = btn; this.base = base; this.hover = hover; }

@Override public void mouseEntered(MouseEvent e) {


if (hover != null) btn.setBackground(hover);

btn.setForeground(hover == null ? PRIMARY_HOVER : Color.WHITE);


}

@Override public void mouseExited(MouseEvent e) {


if (hover != null) btn.setBackground(base);

btn.setForeground(hover == null ? PRIMARY_COLOR : Color.WHITE);


}

}
/* ------------- LOGIN LOGIC (unchanged) ------------- */
private void doLogin() {
String role = comboRole.getSelectedItem().toString();

41
String email = txtEmail.getText().trim();
String pass = String.valueOf(txtPass.getPassword()).trim();
if (email.isEmpty() || pass.isEmpty()) {

JOptionPane.showMessageDialog(this, "Please fill all fields.");


return;

String sql = "SELECT * FROM " + role.toLowerCase() + " WHERE email=?


AND password=?";
try (Connection c = DBConnection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, email);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
JOptionPane.showMessageDialog(this, "Invalid credentials.");
return;

}
switch (role) {
case "Receptionist" -> {
new ReceptionistDashboard(rs.getString("name")).setVisible(true);
dispose();

}
case "Doctor" -> {
new DoctorDashboard(
new DoctorContext(rs.getInt("doctor_id"), rs.getString("name")))
.setVisible(true);

dispose();
}
case "Patient" -> {

42
new PatientDashboard(rs.getInt("patient_id"), rs.getString("name"))
.setVisible(true);
dispose();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "DB Error:\n" + ex.getMessage());
}

}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new LoginFrame().setVisible(true)); }

FORGOT PASSWORD

43
CODE
package hospital.ui.login;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.sql.*;
/**
* Modern, full-width "Forgot Password" dialog (pure
Swing). */

public class ForgotPasswordDialog extends JDialog {

private final JComboBox<String> comboRole = new


JComboBox<>(new String[]{"Doctor", "Patient"});
private final JTextField txtEmail = new JTextField();
private final JPasswordField txtPass = new JPasswordField();
/* ------ theme ------ */

private static final Color CARD_BG = Color.WHITE;


private static final Color BORDER = new Color(0xDDE3EB); private static
final Color PRIMARY = new Color(0x1976D2); private static final Font
FONT_LBL = new Font("SansSerif", Font.PLAIN, 14); private static final
Font FONT_HDR = new Font("SansSerif", Font.BOLD, 20); public
ForgotPasswordDialog(Window owner) {

super(owner, "Reset Password",


ModalityType.APPLICATION_MODAL); buildUI();

pack();
setLocationRelativeTo(owner);
setResizable(false);
}
/* ---------------- UI ---------------- */

44
private void buildUI() {
JPanel card = new JPanel();
card.setBackground(CARD_BG);
card.setBorder(new MatteBorder(1, 1, 4, 4, BORDER));
card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
card.setBorder(new EmptyBorder(25, 35, 25, 35));
add(card);

JLabel heading = new JLabel("Reset Your Password");


heading.setFont(FONT_HDR);

heading.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(heading);

card.add(Box.createRigidArea(new Dimension(0, 20)));


/* full-width fields */

card.add(field("Role", comboRole));

card.add(field("Registered Email", txtEmail));


card.add(field("New Password", txtPass));

card.add(Box.createRigidArea(new Dimension(0, 15)));


/* button */

JButton btnReset = new JButton("Reset Password");


btnReset.setBackground(PRIMARY);

btnReset.setForeground(Color.WHITE);
btnReset.setFocusPainted(false);
btnReset.setAlignmentX(Component.CENTER_ALIGNMENT);
btnReset.setPreferredSize(new Dimension(200, 38));
btnReset.addActionListener(e -> reset());

/* make Enter key activate button */


getRootPane().setDefaultButton(btnReset);
card.add(btnReset);
card.add(Box.createVerticalGlue());
}

45
/* helper: label + component block */
private JPanel field(String label, JComponent input) {
JLabel lbl = new JLabel(label);
lbl.setFont(FONT_LBL);
input.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
input.setPreferredSize(new Dimension(300, 32));

JPanel panel = new JPanel();


panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(lbl);
panel.add(Box.createRigidArea(new Dimension(0, 6)));
panel.add(input);
panel.add(Box.createRigidArea(new Dimension(0, 15)));
return panel;
}
/* ---------------- logic ---------------- */
private void reset() {
String roleTable = comboRole.getSelectedItem().toString().toLowerCase(); // doctor /
patient
String email = txtEmail.getText().trim();
String newPass = String.valueOf(txtPass.getPassword()).trim();
if (email.isEmpty() || newPass.isEmpty()) {

JOptionPane.showMessageDialog(this, "Please fill out every field.",


"Missing Information", JOptionPane.WARNING_MESSAGE); return;

}
String sql = "UPDATE " + roleTable + " SET password=? WHERE
email=?"; try (Connection con = DBConnection.getConnection();

PreparedStatement ps = con.prepareStatement(sql)) {

ps.setString(1, newPass);

46
ps.setString(2, email);
if (ps.executeUpdate() > 0) {
JOptionPane.showMessageDialog(this,
"Password updated – you can now log in.", "Success",
JOptionPane.INFORMATION_MESSAGE); dispose();

} else {
JOptionPane.showMessageDialog(this,
"Email not found.", "Not Found",
JOptionPane.WARNING_MESSAGE); }

} catch (SQLException ex) {


ex.printStackTrace();
JOptionPane.showMessageDialog(this,
"Database error:\n" + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE); }}}

PATIENT REGISTRATION

47
CODE
package hospital.ui.patient;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.sql.*;
/**
* Fully modernized full-width patient registration form (Swing UI)
*/

public class PatientRegistrationFrame extends JFrame {


private final JTextField txtName = new JTextField();
private final JTextField txtAge = new JTextField();
private final JComboBox<String> comboGender = new
JComboBox<>(new String[]{"Male", "Female", "Other"});
private final JTextField txtEmail = new JTextField();
private final JTextField txtPhone = new JTextField();
private final JPasswordField txtPass = new
JPasswordField(); private static final Color PRIMARY = new
Color(0x1976D2); private static final Color BORDER = new
Color(0xDDE3EB); public
PatientRegistrationFrame(Window owner) {

super("New Patient Registration");


setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
buildUI();
pack();
setLocationRelativeTo(owner);
}
private void buildUI() {

48
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.setBorder(new EmptyBorder(25, 35, 25, 35));
content.setBackground(Color.WHITE);

JLabel heading = new JLabel("Patient Registration");


heading.setFont(new Font("SansSerif", Font.BOLD, 20));
heading.setAlignmentX(Component.CENTER_ALIGNMENT);
content.add(heading);

content.add(Box.createRigidArea(new Dimension(0, 20)));


content.add(createField("Full Name", txtName));
content.add(createField("Age", txtAge));

content.add(createField("Gender", comboGender));
content.add(createField("Email Address", txtEmail));
content.add(createField("Phone Number", txtPhone));
content.add(createField("Create Password", txtPass));
content.add(Box.createRigidArea(new Dimension(0, 20)));
JButton btnSave = new JButton("Register");

btnSave.setBackground(PRIMARY);
btnSave.setForeground(Color.WHITE);
btnSave.setFocusPainted(false);
btnSave.setAlignmentX(Component.CENTER_ALIGNMENT);
btnSave.setPreferredSize(new Dimension(200, 40));
btnSave.addActionListener(e -> register());

getRootPane().setDefaultButton(btnSave);
content.add(btnSave);
content.add(Box.createVerticalGlue());
add(content);
}
private JPanel createField(String label, JComponent input)
{ JLabel lbl = new JLabel(label);

49
lbl.setFont(new Font("SansSerif", Font.PLAIN, 14));
input.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
input.setPreferredSize(new Dimension(300, 32));

JPanel panel = new JPanel();


panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(false);

panel.add(lbl);
panel.add(Box.createRigidArea(new Dimension(0, 6)));
panel.add(input);

panel.add(Box.createRigidArea(new Dimension(0, 15)));


return panel;

}
private void register() {
String email = txtEmail.getText().trim();

String checkSql = "SELECT patient_id FROM patient WHERE email=?";

String insertSql = "INSERT INTO patient (name, age, gender, email,


phone, password) "

+ "VALUES (?, ?, ?, ?, ?, ?)";


try (Connection con = DBConnection.getConnection()) {
// Check if patient already exists

try (PreparedStatement ps = con.prepareStatement(checkSql)) {


ps.setString(1, email);

ResultSet rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(this,
"Patient already registered. Please log in.",
"Registration Failed", JOptionPane.WARNING_MESSAGE); return;

50
}
// Insert new patient
try (PreparedStatement ps = con.prepareStatement(insertSql)) {
ps.setString(1, txtName.getText().trim());

ps.setInt(2, Integer.parseInt(txtAge.getText().trim()));
ps.setString(3, comboGender.getSelectedItem().toString());
ps.setString(4, email);

ps.setString(5, txtPhone.getText().trim());
ps.setString(6, String.valueOf(txtPass.getPassword()));
ps.executeUpdate();

JOptionPane.showMessageDialog(this,

"Registration successful! You can now log in.", "Success",


JOptionPane.INFORMATION_MESSAGE); dispose();

} catch (SQLException | NumberFormatException ex) {


ex.printStackTrace();

JOptionPane.showMessageDialog(this,

"Error: " + ex.getMessage(),


"Error", JOptionPane.ERROR_MESSAGE);
}
}
}

51
PATIENT DASHBOARD
CODE
package hospital.ui.patient;
import hospital.ui.login.LoginFrame;
import javax.swing.*;
import java.awt.*;
/**
* Modern Patient Dashboard
* – My profile / appointments / prescriptions / bills
* – Clean top bar with welcome + logout
*/
public class PatientDashboard extends JFrame {
private final int patientId;
private final String patientName;
/* theme */
private static final Color HEADER_BG = Color.WHITE;
private static final Color HEADER_BRD = new Color(0xDDDDDD);

52
private static final Color PRIMARY = new Color(0x1976D2);
public PatientDashboard(int patientId, String name) {

this.patientId = patientId;
this.patientName = name;
setTitle("Patient Dashboard – " + name);
setSize(1000, 650);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
buildUI();
}
/* ---------- UI ---------- */
private void buildUI() {
setLayout(new BorderLayout());
/* --- top bar --- */
JPanel topBar = new JPanel(new BorderLayout());
topBar.setBackground(HEADER_BG);
topBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, HEADER_BRD));
topBar.setPreferredSize(new Dimension(getWidth(), 50));

JLabel lblWelcome = new JLabel("Welcome, " + patientName);


lblWelcome.setFont(new Font("SansSerif", Font.BOLD, 16));
lblWelcome.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
JButton btnLogout = new JButton("Logout");

btnLogout.setBackground(new Color(0xD32F2F));
btnLogout.setForeground(Color.WHITE);
btnLogout.setFocusPainted(false);
btnLogout.setPreferredSize(new Dimension(100, 30));

btnLogout.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnLogout.addActionListener(e -> {

53
dispose();
new LoginFrame().setVisible(true);
});
topBar.add(lblWelcome, BorderLayout.WEST);
topBar.add(btnLogout, BorderLayout.EAST);
add(topBar, BorderLayout.NORTH);
/* --- tabbed panels --- */
JTabbedPane tabs = new
JTabbedPane(JTabbedPane.TOP,
JTabbedPane.SCROLL_TAB_LAYOUT);
tabs.setFont(new Font("SansSerif", Font.PLAIN, 14));
tabs.setBackground(Color.WHITE);
tabs.addTab("Book Appointment", new BookAppointmentPanel(patientId));
tabs.addTab("My Appointments", new ViewAppointmentsPanel(patientId));
tabs.addTab("Prescriptions", new MyPrescriptionsPanel(patientId));
tabs.addTab("My Bills", new MyBillsPanel(patientId)); tabs.addTab("My
Profile", new MyProfilePanel(patientId));

JPanel center = new JPanel(new BorderLayout());


center.setBackground(Color.WHITE);
center.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
center.add(tabs, BorderLayout.CENTER);

add(center, BorderLayout.CENTER);
}

54
PATIENT BOOK APPOINTMENT

CODE
package hospital.ui.patient;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.sql.*;
import java.util.Date;
public class BookAppointmentPanel extends JPanel {
private final int patientId;
private final JComboBox<DoctorItem> cbDoctor = new
JComboBox<>(); private final JSpinner spinDate = new JSpinner(

new SpinnerDateModel(new Date(), null, null,


java.util.Calendar.DAY_OF_MONTH));
private final JSpinner spinTime = new JSpinner(

55
new SpinnerDateModel(new Date(), null, null, java.util.Calendar.MINUTE));
private static final Color PRIMARY = new Color(0x1976D2); private static
final Color BORDER = new Color(0xDDE3EB); public
BookAppointmentPanel(int patientId) {

this.patientId = patientId;
buildUI();
loadDoctors();
}
private void buildUI() {
setLayout(new BorderLayout());
JPanel card = new JPanel();
card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
card.setBackground(Color.WHITE);

card.setBorder(new MatteBorder(1,1,4,4,BORDER));

card.setBorder(new EmptyBorder(25,35,25,35));
add(card);
JLabel hdr = new JLabel("Book Appointment");
hdr.setFont(new Font("SansSerif", Font.BOLD, 20));
hdr.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(hdr);
card.add(Box.createRigidArea(new Dimension(0,20)));
spinDate.setEditor(new JSpinner.DateEditor(spinDate,"yyyy-MM-dd"));
spinTime.setEditor(new JSpinner.DateEditor(spinTime,"HH:mm"));
card.add(field("Doctor", cbDoctor));

card.add(field("Date", spinDate));
card.add(field("Time", spinTime));
card.add(Box.createRigidArea(new Dimension(0,15)));
JButton btnBook = new JButton("Send Request");
btnBook.setBackground(PRIMARY);
btnBook.setForeground(Color.WHITE);

56
btnBook.setPreferredSize(new Dimension(180,38));
btnBook.setFocusPainted(false);
btnBook.setAlignmentX(Component.CENTER_ALIGNMENT);
btnBook.addActionListener(e -> book());

card.add(btnBook);
card.add(Box.createVerticalGlue());
/* SAFE default-button registration */
SwingUtilities.invokeLater(() -> {
JRootPane root = SwingUtilities.getRootPane(BookAppointmentPanel.this); if
(root != null) root.setDefaultButton(btnBook);

});
}
private JPanel field(String label,JComponent input){
JLabel lbl = new JLabel(label);
lbl.setFont(new Font("SansSerif",Font.PLAIN,14));
input.setMaximumSize(new Dimension(Integer.MAX_VALUE,32));
JPanel p = new JPanel();

p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.setOpaque(false);
p.add(lbl); p.add(Box.createRigidArea(new Dimension(0,6))); p.add(input);
p.add(Box.createRigidArea(new Dimension(0,15)));

return p;
}
/* ---------- DB helpers ---------- */
private void loadDoctors(){
try(Connection c=DBConnection.getConnection();
Statement st=c.createStatement();
ResultSet rs=st.executeQuery(
"SELECT doctor_id, name, specialization "
+ "FROM doctor ORDER BY name")){

57
while(rs.next()){
cbDoctor.addItem(new DoctorItem(
rs.getInt(1), rs.getString(2), rs.getString(3))); }

}catch(SQLException ex){ showError(ex); }


}
private void book(){
DoctorItem doc = (DoctorItem) cbDoctor.getSelectedItem();
if(doc==null){

JOptionPane.showMessageDialog(this,"Please choose a doctor.");


return;

}
java.sql.Date dateSql =
new java.sql.Date(((java.util.Date)spinDate.getValue()).getTime());
java.sql.Time timeSql =

new java.sql.Time(((java.util.Date)spinTime.getValue()).getTime());
String sql = """

INSERT INTO appointment


(patient_id, doctor_id, appointment_date,
appointment_time, status, booked_by)
VALUES (?, ?, ?, ?, 'pending', 'patient')
""";
try(Connection c=DBConnection.getConnection();
PreparedStatement ps=c.prepareStatement(sql)){
ps.setInt(1, patientId);
ps.setInt(2, doc.id());
ps.setDate(3, dateSql);
ps.setTime(4, timeSql);
ps.executeUpdate();
JOptionPane.showMessageDialog(this,"Appointment request sent.");

58
}catch(SQLException ex){ showError(ex); }
}

private record DoctorItem(int id,String name,String spec){

@Override public String toString(){ return name+" ("+spec+")"; } }

private void showError(Exception ex){


ex.printStackTrace();
JOptionPane.showMessageDialog(this,
"DB Error: "+ex.getMessage(),
"Database Error", JOptionPane.ERROR_MESSAGE);
}
}

VIEW APPOINTMENT

59
CODE
package hospital.ui.patient;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.sql.*;
/**
* Patient-side view of all appointments with:
* • live search by doctor name
* • cancel PENDING
* • REFRESH button to reload from DB
*/
public class ViewAppointmentsPanel extends
JPanel { /* ---------- theme ---------- */

private static final Color PRIMARY = new Color(0x1976D2);


private static final Color BORDER = new Color(0xDDE3EB);
/* ---------- model / table ---------- */

private final DefaultTableModel model = new DefaultTableModel(


new String[]{"ID", "Doctor", "Date", "Time", "Status"}, 0) { @Override
public boolean isCellEditable(int r, int c) { return false; } };

private final JTable table = new JTable(model);


private final int patientId;
public ViewAppointmentsPanel(int patientId) {
this.patientId = patientId;
setLayout(new BorderLayout());

60
setBackground(new Color(0xF4F7FA));
buildUI();
refresh();
}
/* ---------- UI ---------- */
private void buildUI() {
/* card container */
JPanel card = new JPanel(new BorderLayout(10, 10));
card.setBackground(Color.WHITE);
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 4, 4, BORDER),
BorderFactory.createEmptyBorder(15, 15, 15, 15)));
add(card, BorderLayout.CENTER);
/* table styling */
table.setRowHeight(24);
table.setGridColor(new Color(0xEEEEEE));
JTableHeader th = table.getTableHeader();
th.setReorderingAllowed(false);
th.setFont(new Font("SansSerif", Font.BOLD, 13));

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {


@Override public Component getTableCellRendererComponent( JTable t, Object v,
boolean sel, boolean focus, int row, int col) { Component c =
super.getTableCellRendererComponent(t, v, sel, focus, row, col);
c.setBackground(sel ? t.getSelectionBackground()

: (row % 2 == 0 ? Color.WHITE : new Color(0xF7F9FC))); return c;

}
});
card.add(new JScrollPane(table), BorderLayout.CENTER);

61
/* toolbar */
JPanel bar = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
bar.setOpaque(false);

JButton btnCancel = new JButton("Cancel Pending");


style(btnCancel);
btnCancel.addActionListener(e -> cancelSelected());
/* search box */
JTextField search = new JTextField();
search.setPreferredSize(new Dimension(220, 28));
search.setMaximumSize(new Dimension(220, 28));
search.setToolTipText("Search doctor name");
search.setFont(new Font("SansSerif", Font.PLAIN, 13));
search.getDocument().addDocumentListener(new
javax.swing.event.DocumentListener() {

@Override public void insertUpdate(DocumentEvent e) { filter(search.getText()); }


@Override public void removeUpdate(DocumentEvent e) {
filter(search.getText()); }
@Override public void changedUpdate(DocumentEvent e) {
filter(search.getText()); }
});
/* REFRESH button */
JButton btnRefresh = new JButton("Refresh");
style(btnRefresh);
btnRefresh.setToolTipText("Reload appointments list");
btnRefresh.addActionListener(e -> filter(search.getText())); // reload with current
filter
/* build toolbar */
bar.add(btnCancel);
bar.add(btnRefresh);
bar.add(Box.createHorizontalStrut(15));
bar.add(new JLabel("Search: "));

62
bar.add(search);

bar.add(new JLabel(" 꺎꺌꺍"));

card.add(bar, BorderLayout.NORTH);
}
private void style(JButton b) {
b.setBackground(PRIMARY);
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}

/* ---------- refresh all ---------- */


private void refresh() {
loadQuery("""
SELECT a.appointment_id, d.name, a.appointment_date,
a.appointment_time, a.status

FROM appointment a
JOIN doctor d ON a.doctor_id = d.doctor_id
WHERE a.patient_id = ?
ORDER BY a.appointment_date DESC, a.appointment_time DESC
""", null);

}
/* ---------- filter by doctor ---------- */
private void filter(String txt) {
if (txt.isBlank()) { refresh(); return; }
loadQuery("""
SELECT a.appointment_id, d.name, a.appointment_date,
a.appointment_time, a.status

FROM appointment a
JOIN doctor d ON a.doctor_id = d.doctor_id
WHERE a.patient_id = ? AND d.name LIKE ?

63
ORDER BY a.appointment_date DESC, a.appointment_time DESC
""", "%" + txt + "%");

}
private void loadQuery(String sql, String like) {
model.setRowCount(0);
try (Connection c = DBConnection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, patientId);

if (like != null) ps.setString(2, like);


ResultSet rs = ps.executeQuery();
while (rs.next()) {
model.addRow(new Object[]{
rs.getInt(1),
rs.getString(2),
rs.getDate(3),
rs.getTime(4),
rs.getString(5)
});
}
} catch (SQLException ex) { showError(ex); }
}
/* ---------- cancel ---------- */
private void cancelSelected() {
int row = table.getSelectedRow();
if (row == -1) return;
int id = (int) model.getValueAt(row, 0);
String status = (String) model.getValueAt(row, 4);
if (!"pending".equalsIgnoreCase(status)) {

JOptionPane.showMessageDialog(this,
"Only PENDING appointments can be cancelled.");

64
return;
}
if (JOptionPane.showConfirmDialog(
this, "Cancel appointment " + id + "?", "Confirm",
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return;
try (Connection c = DBConnection.getConnection();

PreparedStatement ps = c.prepareStatement(
"UPDATE appointment SET status='cancelled' " +
"WHERE appointment_id=? AND patient_id=?")) {
ps.setInt(1, id);

ps.setInt(2, patientId);
ps.executeUpdate();
refresh();
} catch (SQLException ex) { showError(ex); }
}
/* ---------- util ---------- */
private void showError(Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
"DB Error: " + ex.getMessage(),
"Database Error", JOptionPane.ERROR_MESSAGE); }

65
PATIENT PRESCRIPTIONS PAGE
CODE
package hospital.ui.patient;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.sql.*;
public class MyPrescriptionsPanel extends JPanel {
/* ---------- theme ---------- */
private static final Color PRIMARY = new Color(0x1976D2);
private static final Color BORDER = new Color(0xDDE3EB);
private static final Color BACK = new Color(0xF4F7FA);
/* ---------- model ---------- */

66
private final DefaultTableModel model = new DefaultTableModel(
new String[]{"App ID", "Doctor", "Date", "Medicines", "Notes"}, 0) {
@Override public boolean isCellEditable(int r,int c){ return false; } };

private final JTable table = new JTable(model);


private final int patientId;
public MyPrescriptionsPanel(int patientId){
this.patientId = patientId;
setLayout(new BorderLayout());
setBackground(BACK);
buildUI();
load("");
}
/* ---------- build UI ---------- */
private void buildUI(){
/* card */
JPanel card = new JPanel(new BorderLayout(10,10));
card.setBackground(Color.WHITE);
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1,1,4,4,BORDER),
BorderFactory.createEmptyBorder(15,15,15,15)));
add(card,BorderLayout.CENTER);
/* table styling */
table.setRowHeight(24);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(70); // App ID
table.getColumnModel().getColumn(1).setPreferredWidth(120); // Doctor
table.getColumnModel().getColumn(2).setPreferredWidth(100); // Date
table.getColumnModel().getColumn(3).setPreferredWidth(220); // Medicines
table.getColumnModel().getColumn(4).setPreferredWidth(220); // Notes

67
table.setGridColor(new Color(0xEEEEEE));
JTableHeader th = table.getTableHeader();
th.setReorderingAllowed(false);
th.setFont(new Font("SansSerif", Font.BOLD, 13));
table.setDefaultRenderer(Object.class,new DefaultTableCellRenderer(){
@Override public Component getTableCellRendererComponent( JTable t,Object
v,boolean sel,boolean focus,int row,int col){ Component c =
super.getTableCellRendererComponent(t,v,sel,focus,row,col);
c.setBackground(sel? t.getSelectionBackground()

:(row%2==0? Color.WHITE : new Color(0xF7F9FC))); return c;

}
});

card.add(new JScrollPane(table),BorderLayout.CENTER);
/* search and refresh bar */
JTextField search = new JTextField();
search.setPreferredSize(new Dimension(250,28));
search.setMaximumSize(new Dimension(250,28));
search.setFont(new Font("SansSerif",Font.PLAIN,13));
search.setToolTipText("Search doctor name or medicine");
search.getDocument().addDocumentListener(new
javax.swing.event.DocumentListener() {
@Override public void insertUpdate(DocumentEvent e){ load(search.getText()); }
@Override public void removeUpdate(DocumentEvent e){ load(search.getText()); }
@Override public void changedUpdate(DocumentEvent e){
load(search.getText()); }
});
JButton btnRefresh = new JButton("Refresh");
style(btnRefresh);

68
btnRefresh.setToolTipText("Reload prescriptions");
btnRefresh.addActionListener(e -> load(search.getText())); JPanel
top = new JPanel(new FlowLayout(FlowLayout.LEFT,8,0));
top.setOpaque(false);

top.add(btnRefresh);
top.add(Box.createHorizontalStrut(12));
top.add(new JLabel("Search: "));

top.add(search); top.add(new JLabel(" 꺎꺌꺍"));


card.add(top,BorderLayout.NORTH);
}
private void style(JButton b){
b.setBackground(PRIMARY);
b.setForeground(Color.WHITE);
b.setFocusPainted(false);

b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}

/* ---------- data loader ---------- */


private void load(String filter){
model.setRowCount(0);
String sql = """
SELECT a.appointment_id, d.name, a.appointment_date,
pr.medicines, pr.notes

FROM prescription pr
JOIN appointment a ON pr.appointment_id = a.appointment_id
JOIN doctor d ON a.doctor_id = d.doctor_id WHERE a.patient_id
= ? AND a.status='completed' %s

ORDER BY a.appointment_date DESC


""".formatted(filter.isBlank() ?
"" : "AND (d.name LIKE ? OR pr.medicines LIKE ?)");

69
try (Connection c = DBConnection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, patientId);

if(!filter.isBlank()){
String like = "%"+filter+"%";
ps.setString(2, like);
ps.setString(3, like);
}
ResultSet rs = ps.executeQuery();
while(rs.next()){
model.addRow(new Object[]{
rs.getInt(1), rs.getString(2),
rs.getDate(3), rs.getString(4),
rs.getString(5)});
}
} catch (SQLException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
"Error loading prescriptions:\n"+ex.getMessage(),
"Database Error", JOptionPane.ERROR_MESSAGE); }

}
}

70
PATIENT VIEW BILL
CODE
package hospital.ui.patient;
import hospital.database.DBConnection;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.sql.*;
public class MyBillsPanel extends JPanel {
/* ---------- theme ---------- */
private static final Color PRIMARY = new Color(0x1976D2);
private static final Color BORDER = new Color(0xDDE3EB);
private static final Color BACK = new Color(0xF4F7FA);
/* ---------- table model ---------- */

71
private final DefaultTableModel model = new DefaultTableModel(
new String[]{"Bill ID", "App ID", "Date", "Amount ₹", "Status",
"Payment Mode"}, 0) {

@Override public boolean isCellEditable(int r, int c) { return false; }


};

private final JTable table = new JTable(model);


private final int patientId;
public MyBillsPanel(int patientId) {
this.patientId = patientId;
setLayout(new BorderLayout());
setBackground(BACK);
buildUI();
load(""); // first load
}
/* ---------- UI build ---------- */
private void buildUI() {
/* card */
JPanel card = new JPanel(new BorderLayout(10, 10));
card.setBackground(Color.WHITE);

card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 4, 4, BORDER),
BorderFactory.createEmptyBorder(15, 15, 15, 15)));
add(card, BorderLayout.CENTER);

/* search + refresh bar */


JTextField search = new JTextField();
search.setPreferredSize(new Dimension(220, 28));
search.setMaximumSize(new Dimension(220, 28));
search.setToolTipText("Search status or payment mode");
search.setFont(new Font("SansSerif", Font.PLAIN, 13));

72
search.getDocument().addDocumentListener(new
javax.swing.event.DocumentListener() {
@Override public void insertUpdate(DocumentEvent e) { load(search.getText()); }
@Override public void removeUpdate(DocumentEvent e) {
load(search.getText()); }
@Override public void changedUpdate(DocumentEvent e) {
load(search.getText()); }
});
JButton btnRefresh = new JButton("Refresh");
style(btnRefresh);
btnRefresh.setToolTipText("Reload bills list");
btnRefresh.addActionListener(e -> load(search.getText()))
JPanel top = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
top.setOpaque(false);

top.add(btnRefresh);
top.add(Box.createHorizontalStrut(12));
top.add(new JLabel("Search: "));
top.add(search);

top.add(new JLabel(" 꺎꺌꺍"));

card.add(top, BorderLayout.NORTH);
/* table styling */
table.setRowHeight(24);
table.setGridColor(new Color(0xEEEEEE));
JTableHeader th = table.getTableHeader();
th.setReorderingAllowed(false);
th.setFont(new Font("SansSerif", Font.BOLD, 13));
/* zebra rows */
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
@Override public Component getTableCellRendererComponent( JTable t, Object v,
boolean sel, boolean focus, int row, int col) { Component c =
super.getTableCellRendererComponent(t, v, sel, focus, row, col);

73
c.setBackground(sel ? t.getSelectionBackground()
: (row % 2 == 0 ? Color.WHITE : new Color(0xF7F9FC))); return c;

}
});
/* column widths */
table.getColumnModel().getColumn(0).setPreferredWidth(70); // Bill ID
table.getColumnModel().getColumn(1).setPreferredWidth(70); // App ID
table.getColumnModel().getColumn(2).setPreferredWidth(100); // Date

card.add(new JScrollPane(table), BorderLayout.CENTER);


}

private void style(JButton b) {


b.setBackground(PRIMARY);
b.setForeground(Color.WHITE);
b.setFocusPainted(false);

b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}

/* ---------- data loader ---------- */

private void load(String filter) {


model.setRowCount(0);
String base = """
SELECT b.bill_id, b.appointment_id, a.appointment_date,
b.total_amount, b.status, COALESCE(b.payment_mode, '-')
FROM bill b

JOIN appointment a ON b.appointment_id = a.appointment_id


WHERE b.patient_id = ?

%s
ORDER BY a.appointment_date DESC """;
String sql = base.formatted(filter.isBlank()

74
? ""
: "AND (b.status LIKE ? OR b.payment_mode LIKE ?)");
try (Connection c = DBConnection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, patientId);

if (!filter.isBlank()) {
String like = "%" + filter + "%";
ps.setString(2, like);
ps.setString(3, like);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
model.addRow(new Object[]{
rs.getInt(1), rs.getInt(2),
rs.getDate(3), rs.getBigDecimal(4),
rs.getString(5), rs.getString(6)});

}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
"Error loading bills:\n" + ex.getMessage(), "Database
Error", JOptionPane.ERROR_MESSAGE); }

}
}

75

You might also like