Priyanshu Kumar SinghReport
Priyanshu Kumar SinghReport
(IMPACT), Patna
Project Report on
“Hospital Management System”
In Partial fulfilment for the award of the degree of
Management System”.
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
Last but not least, I am thankful to my family for their moral support
knowledge and enhance my skills in Java and database development, which will
— Karina Kumari
Session: 2022–2025
CERTIFICATE
This is to certify that the project report entitled “Hospital Management System”
2022–2025,
has been carried out under my supervision in partial fulfilment of the requirements
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
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.
…………………………………………………………
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.
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
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.
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.
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.
Improving patient care quality through accurate medical history access and
faster lab reporting.
Providing scalability, so the hospital can add more users or modules in the
future without reworking the entire system.
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.
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.
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.
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.
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.
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.
Toolkit: javax.swing
Language: Java
Version: Java 21 (LTS)
I/O Database
8
Version Control
Tool: Git
Hosting: GitHub
Tool: JUnit
Documentation
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:
Around 200 MB free disk space for project files and database Standard
IDE (Editor): Apache NetBeans 18 for writing and designing the application
DFDs)
PDF Reader: Adobe Acrobat Reader (for viewing reports, if PDF generation
is added later)
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.
2. Admin Dashboard
Stores patient info like name, age, gender, contact, address, and
admission reason.
4. Appointment Module
11
Allows reception to schedule appointments with doctors.
Stores appointment details like patient ID, doctor ID, date, and
12
Generates bill based on patient treatments, tests, and
discounts.
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.
PK = Primary Key
FK = Foreign Key
NN = NOT NULL
UQ = UNIQUE
DEF = Default
14
1. RECEPTIONIST TABLE:
15
3. PATIENT TABLE:
4. APPOINTMENT TABLE;
16
5. PRESCRIPTION TABLE:
17
8. INVENTORY TABLE:
9. BILL TABLE :
Design Notes
18
2. Security
3. Scalability
4. Extensibility
JAVA 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.
o ArrayList<Patient> patientList
o ArrayList<Appointment> appointments
2. HashMap
3. HashSet
Example use:
o HashSet<String> departmentSet
o HashSet<String> bookedSlots
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:
Patient.java
Doctor.java
Appointment.java
Prescription.java
LabReport.java
InventoryItem.java
Constructors
6. 2D Arrays (Optional/Legacy)
While not a data structure itself, the MVC pattern organizes Java code
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
Appointment Booking
o Doctor Name or ID
2. Doctor Input
Prescription Entry
o Medicines prescribed
o Medical Notes
23
o Date of prescription
Patient Assessment
o Upload Date
Inventory Management
o Quantity in Stock
5. Billing Input
Bill Generation
o Total Amount
24
6. Login and Access Input
To maintain accuracy and prevent invalid entries, the following checks are
enforced: Mandatory fields (e.g., Name, Phone, Password)
25
o View of all prescriptions and uploaded lab reports associated with the
patient.
Prescription Summary
26
3. Receptionist Module Output
o Patient-wise listing of lab results with date and doctor (if referred).
5. Inventory Output
6. Billing Output
27
o Shows final payable after any tax or discount (if applicable).
Payment Status
Dashboard Redirection
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
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 only view their own appointments, prescriptions, lab results, and bill
status.
This structure prevents unauthorized access and ensures data privacy.
3. Input Validation
31
All input fields (registration, appointments, reports) are validated using:
o Character limit checks
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
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:
7. Mandatory Fields
34
All critical fields are marked as required. The form does not proceed
unless: All required fields are filled
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";
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;
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);
/* 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");
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));
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);
}
/* ------------- 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()) {
}
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). */
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);
heading.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(heading);
card.add(field("Role", comboRole));
btnReset.setForeground(Color.WHITE);
btnReset.setFocusPainted(false);
btnReset.setAlignmentX(Component.CENTER_ALIGNMENT);
btnReset.setPreferredSize(new Dimension(200, 38));
btnReset.addActionListener(e -> reset());
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));
}
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); }
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)
*/
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);
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));
panel.add(lbl);
panel.add(Box.createRigidArea(new Dimension(0, 6)));
panel.add(input);
}
private void register() {
String email = txtEmail.getText().trim();
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,
JOptionPane.showMessageDialog(this,
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));
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));
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(
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))); }
}
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 = """
58
}catch(SQLException ex){ showError(ex); }
}
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 ---------- */
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));
}
});
card.add(new JScrollPane(table), BorderLayout.CENTER);
61
/* toolbar */
JPanel bar = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
bar.setOpaque(false);
62
bar.add(search);
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));
}
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);
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; } };
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()
}
});
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: "));
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
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
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) {
card.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 1, 4, 4, BORDER),
BorderFactory.createEmptyBorder(15, 15, 15, 15)));
add(card, BorderLayout.CENTER);
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);
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
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
%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