0% found this document useful (0 votes)
29 views

code

The document outlines a Java Swing application for an E-Health Card System, which includes user authentication, user management, and medical history management. It features a graphical user interface with multiple panels for login, sign-up, and admin/user menus, and utilizes file handling to load and save user data. Key functionalities include adding user details, medications, and medical history, along with error handling for user input and data management.

Uploaded by

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

code

The document outlines a Java Swing application for an E-Health Card System, which includes user authentication, user management, and medical history management. It features a graphical user interface with multiple panels for login, sign-up, and admin/user menus, and utilizes file handling to load and save user data. Key functionalities include adding user details, medications, and medical history, along with error handling for user input and data management.

Uploaded by

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

import javax.swing.

*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.nio.file.*;

public class ehalth {


private static final String ADMIN_USERNAME = "0101";
private static final String ADMIN_PASSWORD = "000010000";
private static final String USER_DATABASE = "C:\\Users\\mikna\\OneDrive\\
Desktop\\EhalthSystem\\users.txt"; // Added

// this

// constant

private static List<User> users = new ArrayList<>();


private static User currentUser = null;

private static JFrame mainFrame;


private static CardLayout cardLayout;
private static JPanel cardPanel;

public static void main(String[] args) {

loadUsersFromFile();

SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}

private static void loadUsersFromFile() {


users.clear(); // Clear existing users

try {
if (!Files.exists(Paths.get(USER_DATABASE))) {
return; // File doesn't exist yet
}

List<String> lines = Files.readAllLines(Paths.get(USER_DATABASE));


for (String line : lines) {
if (!line.trim().isEmpty()) {
User user = User.fromString(line);
if (user != null) {
users.add(user);
}
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error loading user data: " +
e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}

private static void saveUserToFile(User user) {


try {
// Append mode set to true so we don't overwrite existing users
FileWriter fw = new FileWriter(USER_DATABASE, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);

out.println(user.toStringForFile());
out.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error saving user data: " +
e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}

private static void createAndShowGUI() {


mainFrame = new JFrame("E-Health Card System");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(500, 400);
mainFrame.setLocationRelativeTo(null);

cardLayout = new CardLayout();


cardPanel = new JPanel(cardLayout);

// Create panels for different screens


createMainMenuPanel();
createLoginPanel();
createSignUpPanel();
createAdminMenuPanel();
createUserMenuPanel();

mainFrame.add(cardPanel);
mainFrame.setVisible(true);
}

private static void createMainMenuPanel() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

JLabel titleLabel = new JLabel("E-Health Card System",


SwingConstants.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
panel.add(titleLabel, gbc);

JButton loginButton = new JButton("LOG IN");


loginButton.addActionListener(e -> cardLayout.show(cardPanel, "Login"));
panel.add(loginButton, gbc);

JButton signUpButton = new JButton("SIGN UP");


signUpButton.addActionListener(e -> cardLayout.show(cardPanel, "SignUp"));
panel.add(signUpButton, gbc);

JButton exitButton = new JButton("EXIT");


exitButton.addActionListener(e -> System.exit(0));
panel.add(exitButton, gbc);
cardPanel.add(panel, "MainMenu");
}

private static void createLoginPanel() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

JLabel titleLabel = new JLabel("Login", SwingConstants.CENTER);


titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
panel.add(titleLabel, gbc);

JLabel userLabel = new JLabel("Username:");


panel.add(userLabel, gbc);

JTextField userField = new JTextField(15);


panel.add(userField, gbc);

JLabel passLabel = new JLabel("Password:");


panel.add(passLabel, gbc);

JPasswordField passField = new JPasswordField(15);


panel.add(passField, gbc);

JButton loginButton = new JButton("Login");


loginButton.addActionListener(e -> {
String username = userField.getText().trim();
String password = new String(passField.getPassword()).trim();

if (username.equals(ADMIN_USERNAME) && password.equals(ADMIN_PASSWORD))


{
cardLayout.show(cardPanel, "AdminMenu");
} else {
for (User user : users) {
if (user.username.equals(username) &&
user.password.equals(password)) {
currentUser = user;
cardLayout.show(cardPanel, "UserMenu");
return;
}
}
JOptionPane.showMessageDialog(panel, "Invalid credentials",
"Error", JOptionPane.ERROR_MESSAGE);
}
});
panel.add(loginButton, gbc);

JButton backButton = new JButton("Back");


backButton.addActionListener(e -> {
userField.setText("");
passField.setText("");
cardLayout.show(cardPanel, "MainMenu");
});
panel.add(backButton, gbc);

cardPanel.add(panel, "Login");
}
private static void createSignUpPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 10, 5, 10);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

JLabel titleLabel = new JLabel("Sign Up", SwingConstants.CENTER);


titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
panel.add(titleLabel, gbc);

String[] fields = { "Name:", "Age:", "Birthday:", "Civil Status:", "Blood


Type:",
"Contact Number:", "Emergency Contact:", "Username:", "Password (12
digits):" };
JTextField[] textFields = new JTextField[fields.length];
JPasswordField passwordField = new JPasswordField(15);

for (int i = 0; i < fields.length; i++) {


JLabel label = new JLabel(fields[i]);
panel.add(label, gbc);

if (i == fields.length - 1) { // Password field


panel.add(passwordField, gbc);
} else {
textFields[i] = new JTextField(15);
panel.add(textFields[i], gbc);
}
}

JButton signUpButton = new JButton("Sign Up");


signUpButton.addActionListener(e -> {
// Validate password length
if (new String(passwordField.getPassword()).length() != 12) {
JOptionPane.showMessageDialog(panel, "Password must be 12 digits",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

User user = new User();


user.name = textFields[0].getText();
try {
user.age = Integer.parseInt(textFields[1].getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(panel, "Invalid age", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
user.birthday = textFields[2].getText();
user.civilStatus = textFields[3].getText();
user.bloodType = textFields[4].getText();
user.contactNumber = textFields[5].getText();
user.emergencyContactNumber = textFields[6].getText();
user.username = textFields[7].getText();
user.password = new String(passwordField.getPassword());

// Check if username already exists


for (User u : users) {
if (u.username.equals(user.username)) {
JOptionPane.showMessageDialog(panel, "Username already exists",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}

users.add(user);
saveUserToFile(user); // Save the new user to the file

JOptionPane.showMessageDialog(panel, "Account created successfully!",


"Success",
JOptionPane.INFORMATION_MESSAGE);

// Clear fields and go back to main menu


for (JTextField field : textFields) {
if (field != null)
field.setText("");
}
passwordField.setText("");
cardLayout.show(cardPanel, "MainMenu");
});
panel.add(signUpButton, gbc);

JButton backButton = new JButton("Back");


backButton.addActionListener(e -> {
for (JTextField field : textFields) {
if (field != null)
field.setText("");
}
passwordField.setText("");
cardLayout.show(cardPanel, "MainMenu");
});
panel.add(backButton, gbc);

cardPanel.add(panel, "SignUp");
}

private static void createAdminMenuPanel() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

JLabel titleLabel = new JLabel("Welcome Admin", SwingConstants.CENTER);


titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
panel.add(titleLabel, gbc);

String[] options = {
"1. Add User Details",
"2. Add Medication Details",
"3. Add Medical History",
"4. Remove",
"5. Edit",
"6. View Profiles & History", // Updated label
"7. Exit"
};
for (String option : options) {
JButton button = new JButton(option);
button.addActionListener(e -> {
String choice = option.substring(0, 1);
switch (choice) {
case "1" -> showAddUserDetailsDialog();
case "2" -> showAddMedicationDialog();
case "3" -> showAddMedicalHistoryDialog();
case "4" -> showRemoveMenuDialog();
case "5" -> showEditMenuDialog();
case "6" -> showProfilesDialog();
case "7" -> cardLayout.show(cardPanel, "MainMenu");
}
});
panel.add(button, gbc);
}

cardPanel.add(panel, "AdminMenu");
}

private static void createUserMenuPanel() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;

JLabel titleLabel = new JLabel("User Menu", SwingConstants.CENTER);


titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
panel.add(titleLabel, gbc);

JButton profileButton = new JButton("1. Profile");


profileButton.addActionListener(e -> showUserProfile());
panel.add(profileButton, gbc);

JButton medicationButton = new JButton("2. Medication");


medicationButton.addActionListener(e -> showUserMedication());
panel.add(medicationButton, gbc);

JButton historyButton = new JButton("3. Medical History");


historyButton.addActionListener(e -> showUserMedicalHistory());
panel.add(historyButton, gbc);

// Add Manage Account button


JButton manageButton = new JButton("4. Manage Account");
manageButton.addActionListener(e -> showManageAccountDialog());
panel.add(manageButton, gbc);

JButton exitButton = new JButton("5. Exit");


exitButton.addActionListener(e -> {
currentUser = null;
cardLayout.show(cardPanel, "MainMenu");
});
panel.add(exitButton, gbc);

cardPanel.add(panel, "UserMenu");
}

private static void showAddUserDetailsDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"Add User Details",
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

JPanel panel = new JPanel(new GridLayout(0, 1));

// Allergies
JPanel allergyPanel = new JPanel();
allergyPanel.add(new JLabel("Add Allergy:"));
JTextField allergyField = new JTextField(15);
allergyPanel.add(allergyField);
JComboBox<String> severityCombo = new JComboBox<>(new String[] { "mild",
"severe" });
allergyPanel.add(severityCombo);
JButton addAllergyButton = new JButton("Add");
addAllergyButton.addActionListener(e -> {
if (!allergyField.getText().isEmpty()) {
user.allergies.add(allergyField.getText() + " (" +
severityCombo.getSelectedItem() + ")");
allergyField.setText("");
JOptionPane.showMessageDialog(panel, "Allergy added
successfully!");
}
});
allergyPanel.add(addAllergyButton);
panel.add(allergyPanel);

// Medical Conditions
JPanel conditionPanel = new JPanel();
conditionPanel.add(new JLabel("Add Medical Condition:"));
JTextField conditionField = new JTextField(15);
conditionPanel.add(conditionField);
JButton addConditionButton = new JButton("Add");
addConditionButton.addActionListener(e -> {
if (!conditionField.getText().isEmpty()) {
user.medicalConditions.add(conditionField.getText());
conditionField.setText("");
JOptionPane.showMessageDialog(panel, "Medical condition added
successfully!");
}
});
conditionPanel.add(addConditionButton);
panel.add(conditionPanel);

JOptionPane.showMessageDialog(mainFrame, panel, "Add User Details",


JOptionPane.PLAIN_MESSAGE);
}

private static void showAddMedicationDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"Add Medication",
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

JPanel panel = new JPanel(new GridLayout(0, 1));

JTextField medField = new JTextField(15);


JTextField dosageField = new JTextField(15);
JTextField frequencyField = new JTextField(15);
JTextField durationField = new JTextField(15);

panel.add(new JLabel("Medication Name:"));


panel.add(medField);
panel.add(new JLabel("Dosage Amount:"));
panel.add(dosageField);
panel.add(new JLabel("Intake Frequency:"));
panel.add(frequencyField);
panel.add(new JLabel("Start and End Date:"));
panel.add(durationField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Add Medication",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
if (!medField.getText().isEmpty() && !dosageField.getText().isEmpty()
&& !frequencyField.getText().isEmpty() && !
durationField.getText().isEmpty()) {
user.medications.add(new String[] {
medField.getText(),
dosageField.getText(),
frequencyField.getText(),
durationField.getText()
});
JOptionPane.showMessageDialog(mainFrame, "Medication added
successfully!");
}
}
}

private static void showAddMedicalHistoryDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"Add Medical History",
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

JPanel panel = new JPanel(new GridLayout(0, 1));

JTextField historyField = new JTextField(15);


JTextField dateField = new JTextField(15);

panel.add(new JLabel("Medical History:"));


panel.add(historyField);
panel.add(new JLabel("When did it occur/show:"));
panel.add(dateField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Add Medical History",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
if (!historyField.getText().isEmpty() && !
dateField.getText().isEmpty()) {
user.medicalHistory.add(new String[] { historyField.getText(),
dateField.getText() });
JOptionPane.showMessageDialog(mainFrame, "Medical history added
successfully!");
}
}
}

private static void showRemoveMenuDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

String[] options = {
"1. User Account",
"2. User Detail",
"3. User Medication",
"4. User Medical History",
"5. Back"
};

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select an option:",
"Remove Menu",
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);

if (choice == null || choice.endsWith("Back"))


return;

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"Remove " + choice.substring(3),
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

switch (choice.substring(0, 1)) {


case "1" -> {
int confirm = JOptionPane.showConfirmDialog(
mainFrame,
"Are you sure you want to remove this user account?",
"Confirm Removal",
JOptionPane.YES_NO_OPTION);

if (confirm == JOptionPane.YES_OPTION) {
users.remove(user);
JOptionPane.showMessageDialog(mainFrame, "User account
removed.");
}
}
case "2" -> removeUserDetail(user);
case "3" -> removeUserMedication(user);
case "4" -> removeUserMedicalHistory(user);
}
}

private static void removeUserDetail(User user) {


String[] options = { "Allergies", "Medical Conditions" };
String choice = (String) JOptionPane.showInputDialog(
mainFrame,
"Select detail to remove:",
"Remove User Detail",
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);
if (choice == null)
return;

if (choice.equals("Allergies")) {
if (user.allergies.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No allergies to remove.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String allergy = (String) JOptionPane.showInputDialog(


mainFrame,
"Select allergy to remove:",
"Remove Allergy",
JOptionPane.PLAIN_MESSAGE,
null,
user.allergies.toArray(),
user.allergies.get(0));

if (allergy != null) {
user.allergies.remove(allergy);
JOptionPane.showMessageDialog(mainFrame, "Allergy removed.");
}
} else {
if (user.medicalConditions.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medical conditions to
remove.", "Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String condition = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medical condition to remove:",
"Remove Medical Condition",
JOptionPane.PLAIN_MESSAGE,
null,
user.medicalConditions.toArray(),
user.medicalConditions.get(0));

if (condition != null) {
user.medicalConditions.remove(condition);
JOptionPane.showMessageDialog(mainFrame, "Medical condition
removed.");
}
}
}

private static void removeUserMedication(User user) {


if (user.medications.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medications to remove.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String[] medStrings = new String[user.medications.size()];


for (int i = 0; i < user.medications.size(); i++) {
String[] med = user.medications.get(i);
medStrings[i] = med[0] + " - " + med[1] + " - " + med[2] + " - " +
med[3];
}

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medication to remove:",
"Remove Medication",
JOptionPane.PLAIN_MESSAGE,
null,
medStrings,
medStrings[0]);

if (choice != null) {
int index = -1;
for (int i = 0; i < medStrings.length; i++) {
if (medStrings[i].equals(choice)) {
index = i;
break;
}
}
if (index != -1) {
user.medications.remove(index);
JOptionPane.showMessageDialog(mainFrame, "Medication removed.");
}
}
}

private static void removeUserMedicalHistory(User user) {


if (user.medicalHistory.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medical history to
remove.", "Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String[] historyStrings = new String[user.medicalHistory.size()];


for (int i = 0; i < user.medicalHistory.size(); i++) {
String[] history = user.medicalHistory.get(i);
historyStrings[i] = history[0] + " - " + history[1];
}

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medical history to remove:",
"Remove Medical History",
JOptionPane.PLAIN_MESSAGE,
null,
historyStrings,
historyStrings[0]);

if (choice != null) {
int index = -1;
for (int i = 0; i < historyStrings.length; i++) {
if (historyStrings[i].equals(choice)) {
index = i;
break;
}
}
if (index != -1) {
user.medicalHistory.remove(index);
JOptionPane.showMessageDialog(mainFrame, "Medical history
removed.");
}
}
}

private static void showEditMenuDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

String[] options = {
"1. User Detail",
"2. User Medication",
"3. User Medical History",
"4. Back"
};

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select an option:",
"Edit Menu",
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);

if (choice == null || choice.endsWith("Back"))


return;

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"Edit " + choice.substring(3),
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

switch (choice.substring(0, 1)) {


case "1" -> editUserDetail(user);
case "2" -> editUserMedication(user);
case "3" -> editUserMedicalHistory(user);
}
}

private static void editUserDetail(User user) {


String[] options = { "Allergies", "Medical Conditions" };
String choice = (String) JOptionPane.showInputDialog(
mainFrame,
"Select detail to edit:",
"Edit User Detail",
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);

if (choice == null)
return;

if (choice.equals("Allergies")) {
if (user.allergies.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No allergies to edit.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String allergy = (String) JOptionPane.showInputDialog(


mainFrame,
"Select allergy to edit:",
"Edit Allergy",
JOptionPane.PLAIN_MESSAGE,
null,
user.allergies.toArray(),
user.allergies.get(0));

if (allergy != null) {
int index = user.allergies.indexOf(allergy);
String newAllergy = JOptionPane.showInputDialog(
mainFrame,
"Enter new allergy:",
allergy);

if (newAllergy != null && !newAllergy.isEmpty()) {


user.allergies.set(index, newAllergy);
JOptionPane.showMessageDialog(mainFrame, "Allergy updated.");
}
}
} else {
if (user.medicalConditions.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medical conditions to
edit.", "Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String condition = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medical condition to edit:",
"Edit Medical Condition",
JOptionPane.PLAIN_MESSAGE,
null,
user.medicalConditions.toArray(),
user.medicalConditions.get(0));

if (condition != null) {
int index = user.medicalConditions.indexOf(condition);
String newCondition = JOptionPane.showInputDialog(
mainFrame,
"Enter new medical condition:",
condition);

if (newCondition != null && !newCondition.isEmpty()) {


user.medicalConditions.set(index, newCondition);
JOptionPane.showMessageDialog(mainFrame, "Medical condition
updated.");
}
}
}
}

private static void editUserMedication(User user) {


if (user.medications.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medications to edit.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String[] medStrings = new String[user.medications.size()];


for (int i = 0; i < user.medications.size(); i++) {
String[] med = user.medications.get(i);
medStrings[i] = med[0] + " - " + med[1] + " - " + med[2] + " - " +
med[3];
}

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medication to edit:",
"Edit Medication",
JOptionPane.PLAIN_MESSAGE,
null,
medStrings,
medStrings[0]);

if (choice != null) {
int index = -1;
for (int i = 0; i < medStrings.length; i++) {
if (medStrings[i].equals(choice)) {
index = i;
break;
}
}
if (index != -1) {
String[] med = user.medications.get(index);

JPanel panel = new JPanel(new GridLayout(0, 1));


JTextField medField = new JTextField(med[0], 15);
JTextField dosageField = new JTextField(med[1], 15);
JTextField frequencyField = new JTextField(med[2], 15);
JTextField durationField = new JTextField(med[3], 15);

panel.add(new JLabel("Medication Name:"));


panel.add(medField);
panel.add(new JLabel("Dosage Amount:"));
panel.add(dosageField);
panel.add(new JLabel("Intake Frequency:"));
panel.add(frequencyField);
panel.add(new JLabel("Start and End Date:"));
panel.add(durationField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Edit Medication",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
if (!medField.getText().isEmpty() && !
dosageField.getText().isEmpty()
&& !frequencyField.getText().isEmpty() && !
durationField.getText().isEmpty()) {
user.medications.set(index, new String[] {
medField.getText(),
dosageField.getText(),
frequencyField.getText(),
durationField.getText()
});
JOptionPane.showMessageDialog(mainFrame, "Medication
updated successfully!");
}
}
}
}
}

private static void editUserMedicalHistory(User user) {


if (user.medicalHistory.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medical history to edit.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

String[] historyStrings = new String[user.medicalHistory.size()];


for (int i = 0; i < user.medicalHistory.size(); i++) {
String[] history = user.medicalHistory.get(i);
historyStrings[i] = history[0] + " - " + history[1];
}

String choice = (String) JOptionPane.showInputDialog(


mainFrame,
"Select medical history to edit:",
"Edit Medical History",
JOptionPane.PLAIN_MESSAGE,
null,
historyStrings,
historyStrings[0]);

if (choice != null) {
int index = -1;
for (int i = 0; i < historyStrings.length; i++) {
if (historyStrings[i].equals(choice)) {
index = i;
break;
}
}
if (index != -1) {
String[] history = user.medicalHistory.get(index);

JPanel panel = new JPanel(new GridLayout(0, 1));


JTextField historyField = new JTextField(history[0], 15);
JTextField dateField = new JTextField(history[1], 15);

panel.add(new JLabel("Medical History:"));


panel.add(historyField);
panel.add(new JLabel("When did it occur/show:"));
panel.add(dateField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Edit Medical History",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
if (!historyField.getText().isEmpty() && !
dateField.getText().isEmpty()) {
user.medicalHistory.set(index, new String[]
{ historyField.getText(), dateField.getText() });
JOptionPane.showMessageDialog(mainFrame, "Medical history
updated successfully!");
}
}
}
}
}

private static void showProfilesDialog() {


if (users.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No users available.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

User user = (User) JOptionPane.showInputDialog(


mainFrame,
"Select a user:",
"View Profile",
JOptionPane.PLAIN_MESSAGE,
null,
users.toArray(),
users.get(0));

if (user == null)
return;

// Create a tabbed pane to show both profile and medical history


JTabbedPane tabbedPane = new JTabbedPane();

// Profile tab
JPanel profilePanel = new JPanel(new BorderLayout());
JTextArea profileText = new JTextArea();
profileText.setEditable(false);
profileText.append("Name: " + user.name + "\n");
profileText.append("Age: " + user.age + "\n");
profileText.append("Birthday: " + user.birthday + "\n");
profileText.append("Civil Status: " + user.civilStatus + "\n");
profileText.append("Blood Type: " + user.bloodType + "\n");
profileText.append("Contact Number: " + user.contactNumber + "\n");
profileText.append("Emergency Contact: " + user.emergencyContactNumber + "\
n");
profileText.append("Allergies: " + user.allergies + "\n");
profileText.append("Medical Conditions: " + user.medicalConditions + "\n");
profilePanel.add(new JScrollPane(profileText), BorderLayout.CENTER);
tabbedPane.addTab("Profile", profilePanel);

// Medical History tab


JPanel historyPanel = new JPanel(new BorderLayout());
JTextArea historyText = new JTextArea();
historyText.setEditable(false);
if (user.medicalHistory.isEmpty()) {
historyText.append("No medical history available.");
} else {
for (String[] history : user.medicalHistory) {
historyText.append("• " + history[0] + "\n");
historyText.append(" Occurred: " + history[1] + "\n\n");
}
}
historyPanel.add(new JScrollPane(historyText), BorderLayout.CENTER);
tabbedPane.addTab("Medical History", historyPanel);

JOptionPane.showMessageDialog(mainFrame, tabbedPane,
"User Profile - " + user.name, JOptionPane.PLAIN_MESSAGE);
}

private static void showUserProfile() {


if (currentUser == null)
return;

StringBuilder profile = new StringBuilder();


profile.append("Name: ").append(currentUser.name).append("\n");
profile.append("Age: ").append(currentUser.age).append("\n");
profile.append("Birthday: ").append(currentUser.birthday).append("\n");
profile.append("Civil Status: ").append(currentUser.civilStatus).append("\
n");
profile.append("Blood Type: ").append(currentUser.bloodType).append("\n");
profile.append("Contact Number:
").append(currentUser.contactNumber).append("\n");
profile.append("Emergency Contact:
").append(currentUser.emergencyContactNumber).append("\n");
profile.append("Allergies: ").append(currentUser.allergies).append("\n");
profile.append("Medical Conditions:
").append(currentUser.medicalConditions).append("\n");

JOptionPane.showMessageDialog(mainFrame, profile.toString(), "Your


Profile", JOptionPane.INFORMATION_MESSAGE);
}

private static void showUserMedication() {


if (currentUser == null || currentUser.medications.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "No medications available.",
"Info",
JOptionPane.INFORMATION_MESSAGE);
return;
}

StringBuilder meds = new StringBuilder();


for (String[] med : currentUser.medications) {
meds.append("Medicine: ").append(med[0]).append("\n");
meds.append("Dosage: ").append(med[1]).append("\n");
meds.append("Frequency: ").append(med[2]).append("\n");
meds.append("Duration: ").append(med[3]).append("\n");
meds.append("---\n");
}

JOptionPane.showMessageDialog(mainFrame, meds.toString(), "Your


Medications", JOptionPane.INFORMATION_MESSAGE);
}

private static void showUserMedicalHistory() {


if (currentUser == null)
return;

JPanel panel = new JPanel(new BorderLayout());


JTextArea historyText = new JTextArea();
historyText.setEditable(false);

if (currentUser.medicalHistory.isEmpty()) {
historyText.append("No medical history available.");
} else {
historyText.append("Your Medical History:\n\n");
for (String[] history : currentUser.medicalHistory) {
historyText.append("• " + history[0] + "\n");
historyText.append(" Occurred: " + history[1] + "\n\n");
}
}

panel.add(new JScrollPane(historyText), BorderLayout.CENTER);


JOptionPane.showMessageDialog(mainFrame, panel,
"Medical History", JOptionPane.PLAIN_MESSAGE);
}

private static void showManageAccountDialog() {


if (currentUser == null)
return;

String[] options = { "Update Username", "Update Password", "Cancel" };


int choice = JOptionPane.showOptionDialog(mainFrame,
"What would you like to update?",
"Manage Account",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);

if (choice == 0) { // Update Username


updateUsername();
} else if (choice == 1) { // Update Password
updatePassword();
}
}

private static void updateUsername() {


JPanel panel = new JPanel(new GridLayout(0, 1));
JTextField newUsernameField = new JTextField(15);
JTextField confirmUsernameField = new JTextField(15);

panel.add(new JLabel("New Username:"));


panel.add(newUsernameField);
panel.add(new JLabel("Confirm Username:"));
panel.add(confirmUsernameField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Update Username",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
String newUsername = newUsernameField.getText().trim();
String confirmUsername = confirmUsernameField.getText().trim();

if (!newUsername.equals(confirmUsername)) {
JOptionPane.showMessageDialog(mainFrame, "Usernames don't match!",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

if (newUsername.isEmpty()) {
JOptionPane.showMessageDialog(mainFrame, "Username cannot be
empty!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

// Check if username already exists


for (User user : users) {
if (user.username.equals(newUsername)) {
JOptionPane.showMessageDialog(mainFrame, "Username already
exists!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}

currentUser.username = newUsername;
updateDatabaseFile();
JOptionPane.showMessageDialog(mainFrame, "Username updated
successfully!");
}
}

private static void updatePassword() {


JPanel panel = new JPanel(new GridLayout(0, 1));
JPasswordField newPasswordField = new JPasswordField(15);
JPasswordField confirmPasswordField = new JPasswordField(15);
panel.add(new JLabel("New Password (12 digits):"));
panel.add(newPasswordField);
panel.add(new JLabel("Confirm Password:"));
panel.add(confirmPasswordField);

int result = JOptionPane.showConfirmDialog(


mainFrame,
panel,
"Update Password",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
String newPassword = new String(newPasswordField.getPassword()).trim();
String confirmPassword = new
String(confirmPasswordField.getPassword()).trim();

if (!newPassword.equals(confirmPassword)) {
JOptionPane.showMessageDialog(mainFrame, "Passwords don't match!",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}

if (newPassword.length() != 12) {
JOptionPane.showMessageDialog(mainFrame, "Password must be 12
digits!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

currentUser.password = newPassword;
updateDatabaseFile();
JOptionPane.showMessageDialog(mainFrame, "Password updated
successfully!");
}
}

private static void updateDatabaseFile() {


try {
// Overwrite the entire file with updated user data
FileWriter fw = new FileWriter(USER_DATABASE, false); // false to
overwrite
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);

for (User user : users) {


out.println(user.toStringForFile());
}
out.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error updating user data: " +
e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}

static class User {


String name, birthday, civilStatus, bloodType;
String contactNumber, emergencyContactNumber;
String username, password;
int age;
List<String> allergies = new ArrayList<>();
List<String> medicalConditions = new ArrayList<>();
List<String[]> medications = new ArrayList<>();
List<String[]> medicalHistory = new ArrayList<>();

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

public String getMedicalHistoryAsString() {


if (medicalHistory.isEmpty()) {
return "No medical history available.";
}

StringBuilder sb = new StringBuilder();


for (String[] history : medicalHistory) {
sb.append("• ").append(history[0]).append("\n");
sb.append(" Occurred: ").append(history[1]).append("\n\n");
}
return sb.toString();
}

public String toStringForFile() {


return String.join(",",
name,
String.valueOf(age),
birthday,
civilStatus,
bloodType,
contactNumber,
emergencyContactNumber,
username,
password,
String.join(";", allergies),
String.join(";", medicalConditions),
serializeStringList(medications),
serializeStringList(medicalHistory));
}

public static User fromString(String data) {


try {
String[] parts = data.split(",", -1); // -1 keeps empty values
if (parts.length < 10)
return null; // Basic validation

User user = new User();


user.name = parts[0];
user.age = Integer.parseInt(parts[1]);
user.birthday = parts[2];
user.civilStatus = parts[3];
user.bloodType = parts[4];
user.contactNumber = parts[5];
user.emergencyContactNumber = parts[6];
user.username = parts[7];
user.password = parts[8];
// Parse allergies
if (!parts[9].isEmpty()) {
String[] allergyArray = parts[9].split(";");
for (String allergy : allergyArray) {
if (!allergy.isEmpty())
user.allergies.add(allergy);
}
}

// Parse medical conditions


if (!parts[10].isEmpty()) {
String[] conditionArray = parts[10].split(";");
for (String condition : conditionArray) {
if (!condition.isEmpty())
user.medicalConditions.add(condition);
}
}

// Parse medications (if exists in file)


if (parts.length > 11 && !parts[11].isEmpty()) {
String[] meds = parts[11].split(";");
for (String med : meds) {
if (!med.isEmpty()) {
String[] medParts = med.split("\\|");
if (medParts.length == 4) {
user.medications.add(medParts);
}
}
}
}

// Parse medical history (if exists in file)


if (parts.length > 12 && !parts[12].isEmpty()) {
String[] histories = parts[12].split(";");
for (String history : histories) {
if (!history.isEmpty()) {
String[] historyParts = history.split("\\|");
if (historyParts.length == 2) {
user.medicalHistory.add(historyParts);
}
}
}
}

return user;
} catch (Exception e) {
return null;
}
}

private static String serializeStringList(List<String[]> list) {


StringBuilder sb = new StringBuilder();
for (String[] item : list) {
sb.append(String.join("|", item)).append(";");
}
return sb.toString();
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy