A comprehensive desktop application for managing hospital operations including patient records, doctor management, appointments, and medical checkups. Built with Java Swing and MySQL database.
- Overview
- Features
- System Architecture
- Technology Stack
- Database Schema
- Installation and Setup
- Usage Guide
- Code Structure
- Security Considerations
- Contributing
- License
MediSense HMS is a role-based hospital management system that provides separate interfaces for three types of users:
- Administrators - Manage doctors and patients
- Doctors - View patients, add checkups, and manage appointments
- Patients - View appointments, medical records, and personal profile
The system implements a complete CRUD (Create, Read, Update, Delete) functionality for managing hospital data with a modern graphical user interface.
- Role-based login (Admin, Doctor, Patient)
- Secure password authentication
- User session management
- Logout functionality with confirmation
-
Doctor Management
- Add new doctors with auto-generated IDs (DR000001 format)
- Update doctor information (name, specialization, email, phone)
- Delete doctors with cascade deletion
- View all doctors in tabular format
- Default password: DOC@1234
-
Patient Management
- Add new patients with auto-generated IDs (PT000001 format)
- Update patient information (name, age, email, phone)
- Delete patients with cascade deletion
- View all patients in tabular format
- Default password: PAT@1234
-
Dashboard View
- Statistics cards showing today's appointments, total patients, and pending checkups
- Today's appointment list
- Welcome message with doctor's name
-
My Patients
- View all patients assigned to the doctor
- Patient details in tabular format
-
Add Checkup
- Record medical checkups for patients
- Add diagnosis, prescription, and notes
-
Appointments
- View scheduled appointments
- Manage appointment status
-
Dashboard View
- Statistics cards showing total visits, upcoming appointments, and medical records
- Recent appointments list
- Welcome message with patient's name
-
My Appointments
- View all scheduled appointments
- Appointment details and status
-
Medical Records
- Access complete medical history
- View checkup details, diagnoses, and prescriptions
-
Profile
- View personal information
- Contact details
The application follows a modular architecture with clear separation of concerns:
mediSense-HMS/
├── src/hospital/management/system/
│ ├── Login.java # Main entry point and authentication
│ ├── loginDB.java # Database connection and authentication logic
│ ├── adminDashboard.java # Admin interface and operations
│ ├── doctorDashboard.java # Doctor interface and operations
│ └── patientDashboard.java # Patient interface and operations
├── assets/
│ ├── logo.png # Application logo
│ ├── admin.png # Admin icon
│ └── doctor.png # Doctor icon
└── Hospital Management System.iml
- Language: Java
- GUI Framework: Java Swing
- Database: MySQL 8.0
- JDBC Driver: MySQL Connector/J (com.mysql.cj.jdbc.Driver)
- Development Environment: IntelliJ IDEA
- Java Version: Java 8 or higher
Stores authentication credentials for all users.
CREATE TABLE login (
id VARCHAR(20) PRIMARY KEY,
pass VARCHAR(100) NOT NULL,
user_type ENUM('Admin', 'Doctor', 'Patient') NOT NULL
);Stores detailed information about doctors.
CREATE TABLE doctor_details (
doctor_id VARCHAR(20) PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
specialization VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(20),
join_date DATE,
FOREIGN KEY (doctor_id) REFERENCES login(id) ON DELETE CASCADE
);Stores detailed information about patients.
CREATE TABLE patient_details (
patient_id VARCHAR(20) PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
age INT,
email VARCHAR(100),
phone VARCHAR(20),
registration_date DATE,
FOREIGN KEY (patient_id) REFERENCES login(id) ON DELETE CASCADE
);- Java Development Kit (JDK) 8 or higher
- MySQL Server 8.0 or higher
- MySQL Connector/J JDBC driver
- IDE (IntelliJ IDEA recommended)
-
Install MySQL Server and start the service.
-
Create the database:
CREATE DATABASE medisense;
USE medisense;-
Create the required tables using the SQL schema provided above.
-
Create an admin user for initial access:
INSERT INTO login (id, pass, user_type) VALUES ('admin', 'admin123', 'Admin');- Update database credentials in
loginDB.java:
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/medisense",
"your_mysql_username",
"your_mysql_password"
);- Clone the repository:
git clone https://github.com/itzsouravkumar/mediSense-HMS.git
cd mediSense-HMS-
Add MySQL Connector/J to your project classpath:
- Download MySQL Connector/J from the official MySQL website
- Add the JAR file to your project's library path
-
Ensure the
assetsfolder is in the project root directory with all image files. -
Compile and run the application:
javac src/hospital/management/system/*.java
java -cp .:mysql-connector-java.jar src.hospital.management.system.LoginOr run directly from your IDE:
- Open the project in IntelliJ IDEA
- Configure the MySQL JDBC driver in project dependencies
- Run
Login.java
- Start the application by running
Login.java - Log in with the admin credentials (id: admin, pass: admin123)
- Add doctors and patients through the Admin Dashboard
- Use the generated IDs and default passwords for doctor/patient login
-
Adding a Doctor:
- Navigate to "Doctors" tab
- Fill in the form (Name, Specialization, Email, Phone)
- Click "Add" button
- System generates unique ID (e.g., DR000001)
- Default password: DOC@1234
-
Adding a Patient:
- Navigate to "Patients" tab
- Fill in the form (Name, Age, Email, Phone)
- Click "Add" button
- System generates unique ID (e.g., PT000001)
- Default password: PAT@1234
-
Updating Records:
- Select a row in the table
- Form auto-populates with selected data
- Modify the fields
- Click "Update" button
-
Deleting Records:
- Select a row in the table
- Click "Delete" button
- Confirm the deletion
- Related login credentials are removed automatically
-
View Dashboard:
- Shows statistics: today's appointments, total patients, pending checkups
- Displays today's appointment schedule
-
Manage Patients:
- Navigate to "My Patients"
- View complete patient list
- Access patient details
-
Add Checkup:
- Navigate to "Add Checkup"
- Select patient
- Enter diagnosis, prescription, and notes
- Save checkup record
-
View Appointments:
- Navigate to "Appointments"
- View all scheduled appointments
- Check appointment details and status
-
View Dashboard:
- Shows statistics: total visits, upcoming appointments, medical records count
- Displays recent appointments
-
Check Appointments:
- Navigate to "My Appointments"
- View all scheduled appointments
- Check date, time, and doctor information
-
Access Medical Records:
- Navigate to "Medical Records"
- View complete medical history
- Access checkup details, diagnoses, and prescriptions
-
View Profile:
- Navigate to "Profile"
- View personal information
- Check contact details
Main application entry point that handles user authentication and dashboard routing.
Key Components:
JTextField textField- Username input fieldJPasswordField passwordField- Password input fieldJRadioButton- Role selection (Admin, Doctor, Patient)JButton loginButton- Custom styled login button with hover effects
Key Methods:
Login()- Constructor that initializes the login UI with custom stylinggetJPanel()- Creates the rounded panel container with shadow effectsactionPerformed(ActionEvent e)- Handles login button click, validates credentials, and routes to appropriate dashboardshowLoginScreen()- Restores login screen after logout, recreates all UI components
Authentication Flow:
- Validates role selection and input fields
- Queries database using loginDB connection
- On success, replaces login panel with role-specific dashboard
- On failure, shows error dialog
Database connection manager and authentication service.
Key Components:
Connection connection- MySQL database connection instance- Database URL:
jdbc:mysql://localhost:3306/medisense
Key Methods:
loginDB()- Constructor that establishes database connection using MySQL Connector/JgetConnection()- Returns the active database connectionauthenticateUser(String id, String password, String role)- Validates user credentials against login table
Database Configuration:
- Driver:
com.mysql.cj.jdbc.Driver - Connection pooling: Single connection instance per loginDB object
- Error handling: Prints stack trace on connection failure
Administrator interface with comprehensive CRUD operations for managing doctors and patients.
Key Components:
DefaultTableModel doctorModel- Table model for doctor dataDefaultTableModel patientModel- Table model for patient dataJTable doctorTable- Doctor records tableJTable patientTable- Patient records table- Input fields for doctor and patient information
Key Methods:
adminDashboard(String username, String role, Login loginFrame)- Constructor that initializes tabbed interfacegetConnection()- Retrieves database connection via loginDBgetNextId(Connection con, String table, String idColumn, String prefix)- Generates sequential IDs (DR000001, PT000001)
Doctor Management Methods:
loadDoctors()- Fetches all doctors from database and populates tablepopulateDoctorFormFromSelection()- Fills form when table row is selectedaddDoctor()- Inserts new doctor with transaction management (login + doctor_details)updateSelectedDoctor()- Updates existing doctor informationdeleteSelectedDoctor()- Removes doctor with cascade deletion confirmationclearDoctorForm()- Resets all form fields
Patient Management Methods:
loadPatients()- Fetches all patients from database and populates tablepopulatePatientFormFromSelection()- Fills form when table row is selectedaddPatient()- Inserts new patient with transaction management (login + patient_details)updateSelectedPatient()- Updates existing patient informationdeleteSelectedPatient()- Removes patient with cascade deletion confirmationclearPatientForm()- Resets all form fields
Transaction Management:
- Uses
setAutoCommit(false)for atomic operations - Commits on success, rolls back on failure
- Ensures data consistency between login and details tables
Doctor interface for patient management, checkups, and appointments.
Key Components:
String loggedInUserName- Stores logged-in doctor's usernameString loggedInUserRole- Stores user role (Doctor)Login loginFrame- Reference to main login frame for navigationJPanel contentPanel- Dynamic content area that changes based on navigation
Key Methods:
doctorDashboard(String username, String role, Login loginFrame)- Constructor that initializes sidebar and content areacreateSidebar()- Builds navigation sidebar with menu items (Dashboard, My Patients, Add Checkup, Appointments)createContentPanel()- Initializes the main content display areahandleNavigation(String item)- Routes to appropriate view based on menu selection
Dashboard Views:
-
loadDashboardView()- Displays statistics cards and today's appointments- Fetches: today's appointment count, total patient count, pending checkups
- Shows: welcome message with doctor's name, quick stats, appointment list
-
loadMyPatientsView()- Shows all patients assigned to the doctor- Displays patient table with ID, name, age, contact information
-
loadAddCheckupView()- Provides form for recording medical checkups- Fields: patient selection, diagnosis, prescription, notes
- Saves checkup data with timestamp
-
loadAppointmentsView()- Lists all scheduled appointments- Shows: appointment date, time, patient name, status
Helper Methods:
getDoctorName(loginDB db)- Retrieves doctor's full name from databasegetTodayAppointments(loginDB db)- Counts appointments for current dategetMyPatientCount(loginDB db)- Returns total number of patientsgetPendingCheckups(loginDB db)- Counts incomplete checkupscreateStatCard(String title, int value, Color color, int x, int y)- Creates visual statistic cards
UI Features:
- Custom avatar circles with initials
- Hover effects on navigation buttons
- Logout confirmation dialog
- Profile panel showing doctor name and role
Patient interface for viewing appointments, medical records, and personal profile.
Key Components:
String loggedInUserName- Stores logged-in patient's usernameString loggedInUserRole- Stores user role (Patient)Login loginFrame- Reference to main login frame for navigationJPanel contentPanel- Dynamic content area for different views
Key Methods:
patientDashboard(String username, String role, Login loginFrame)- Constructor that sets up patient interfacecreateSidebar()- Builds navigation sidebar with menu items (Dashboard, My Appointments, Medical Records, Profile)createContentPanel()- Initializes the main display areahandleNavigation(String item)- Switches between different patient views
Dashboard Views:
-
loadDashboardView()- Shows patient statistics and recent activity- Displays: total visits, upcoming appointments, medical records count
- Shows: welcome message, quick stats, recent appointments
-
loadAppointmentsView()- Lists all patient appointments- Shows: date, time, doctor name, appointment status
- Allows viewing appointment details
-
loadMedicalRecordsView()- Displays complete medical history- Shows: checkup date, doctor name, diagnosis, prescription
- Provides access to historical medical data
-
loadProfileView()- Shows patient personal information- Displays: full name, age, email, phone, registration date
- Read-only view of patient details
Helper Methods:
getPatientName(loginDB db)- Retrieves patient's full name from databasegetTotalVisits(loginDB db)- Counts total hospital visitsgetUpcomingAppointments(loginDB db)- Returns count of future appointmentsgetMedicalRecordsCount(loginDB db)- Counts total medical recordscreateStatCard(String title, int value, Color color, int x, int y)- Creates visual statistic displays
UI Features:
- Custom avatar with patient's initial
- Smooth navigation transitions
- Logout confirmation dialog
- Profile section with patient info
- Color-coded statistics cards (blue, green, purple themes)
- Basic password authentication
- Role-based access control
- SQL injection vulnerability in Login.java (concatenated queries)
- Plain text password storage
- Default passwords for new users
-
Password Security:
- Implement password hashing (BCrypt, PBKDF2)
- Enforce strong password policies
- Add password change functionality
- Implement password reset mechanism
-
SQL Injection Prevention:
- Replace concatenated SQL queries with PreparedStatements
- Current vulnerable code in Login.java line 206:
// VULNERABLE String query = "SELECT * FROM login WHERE id='" + username + "' AND pass='" + password + "' AND user_type='" + role + "'"; // SECURE ALTERNATIVE String query = "SELECT * FROM login WHERE id=? AND pass=? AND user_type=?"; PreparedStatement ps = connection.prepareStatement(query); ps.setString(1, username); ps.setString(2, password); ps.setString(3, role);
-
Session Management:
- Implement session timeouts
- Add session invalidation on logout
- Track active sessions
-
Access Control:
- Add authorization checks for sensitive operations
- Implement audit logging
- Track user actions
-
Data Validation:
- Validate all user inputs
- Sanitize data before database operations
- Implement input length restrictions
-
Database Security:
- Use environment variables for database credentials
- Implement connection pooling
- Use SSL/TLS for database connections
- Regular database backups
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow Java naming conventions
- Add comments for complex logic
- Write unit tests for new features
- Update documentation as needed
This project is part of an educational initiative. Please check with the repository owner for specific licensing terms.
Project Repository: https://github.com/itzsouravkumar/mediSense-HMS
- Java Swing documentation
- MySQL community
- IntelliJ IDEA
- All contributors to this project
Future Enhancements
MediSense HMS is built with scalability in mind. Future updates aim to introduce:
Appointment Notifications via email or SMS for doctors and patients
E-Prescription System with downloadable PDFs
Billing & Invoicing Module for patient payments and hospital accounting
Inventory Management for medicines and medical supplies
Data Analytics Dashboard to monitor hospital performance metric