How to update a data from a hashmap that’s in different classes?

I’m trying to figure out how I can update, or change my data in a GUI program. Initially I worked through updating it without the verification through user.id, and it worked. But I figured out that I needed the verification to feel the user make more secure. I tried making a boolean statement for it, and when I tried it the verification doesnt work even if I’m inputting the right work.id upon log in.

My initial guess is to remove the population that I inputted on my data IDandPasswords class, but if so how do I need to properly approach this?

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;

public class LoginPage implements Runnable {
    private static final String EMPTY = "          ";
    private static final String LOGIN = "Login";
    private static final String REGISTRATION = "Registration";

    private CardLayout cardLayout;
    private JFrame frame;
    private JLabel messageLabel;
    private JPanel cardPanel;
    private JPasswordField userPasswordField;
    private JTextField userIdField;
    private Map<String, IDandPasswords.UserInfo> loginInfo;

    public LoginPage(Map<String, IDandPasswords.UserInfo> loginInfo) {
        this.loginInfo = loginInfo;
    }

    public void run() {
        createAndDisplayGui();
    }

    private void createAndDisplayGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createCardPanel(), BorderLayout.CENTER);
        JMenuBar menuBar = new JMenuBar();
        JMenuItem loginMenuItem = new JMenuItem("Login");
        loginMenuItem.addActionListener(this::showLogin);
        JMenuItem registerMenuItem = new JMenuItem("Register");
        registerMenuItem.addActionListener(this::showRegistration);
        menuBar.add(loginMenuItem);
        menuBar.add(registerMenuItem);
        frame.setJMenuBar(menuBar);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createCardPanel() {
        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);
        cardPanel.add(createLoginPanel(), LOGIN);
        cardPanel.add(createRegistrationPanel(), REGISTRATION);
        return cardPanel;
    }

    private JPanel createLoginButtonsPanel() {
        JPanel loginButtonsPanel = new JPanel();
        JButton loginButton = new JButton(LOGIN);
        loginButton.addActionListener(this::doLogin);
        loginButtonsPanel.add(loginButton);
        JButton resetButton = new JButton("Reset");
        resetButton.addActionListener(this::reset);
        loginButtonsPanel.add(resetButton);
        return loginButtonsPanel;
    }

    private JPanel createLoginFormPanel() {
        JPanel loginFormPanel = new JPanel(new GridLayout(0, 2, 5, 10));
        loginFormPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        JLabel userIdLabel = new JLabel("User ID");
        loginFormPanel.add(userIdLabel);
        userIdField = new JTextField(10);
        loginFormPanel.add(userIdField);
        JLabel userPasswordLabel = new JLabel("Password");
        loginFormPanel.add(userPasswordLabel);
        userPasswordField = new JPasswordField(10);
        loginFormPanel.add(userPasswordField);
        return loginFormPanel;
    }

    private JPanel createLoginPanel() {
        JPanel loginPanel = new JPanel(new BorderLayout());
        messageLabel = new JLabel(EMPTY, JLabel.CENTER);
        loginPanel.add(messageLabel, BorderLayout.PAGE_START);
        loginPanel.add(createLoginFormPanel(), BorderLayout.CENTER);
        loginPanel.add(createLoginButtonsPanel(), BorderLayout.PAGE_END);
        return loginPanel;
    }

    private JPanel createRegistrationPanel() {
        JPanel registrationPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel userIDLabel = new JLabel("User ID:");
        registrationPanel.add(userIDLabel, gbc);
        JTextField userIDField = new JTextField(10);
        gbc.gridx = 1;
        registrationPanel.add(userIDField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel firstNameLabel = new JLabel("First Name:");
        registrationPanel.add(firstNameLabel, gbc);
        JTextField firstNameField = new JTextField(10);
        gbc.gridx = 1;
        registrationPanel.add(firstNameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel lastNameLabel = new JLabel("Last Name:");
        registrationPanel.add(lastNameLabel, gbc);
        JTextField lastNameField = new JTextField(10);
        gbc.gridx = 1;
        registrationPanel.add(lastNameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        JLabel passwordLabel = new JLabel("Password:");
        registrationPanel.add(passwordLabel, gbc);
        JPasswordField passwordField = new JPasswordField(10);
        gbc.gridx = 1;
        registrationPanel.add(passwordField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        JButton registrationButton = new JButton(REGISTRATION);
        registrationButton.addActionListener(e -> registerUser(userIDField.getText(), firstNameField.getText(), lastNameField.getText(), new String(passwordField.getPassword())));
        registrationPanel.add(registrationButton, gbc);

        return registrationPanel;
    }

    private void doLogin(ActionEvent event) {
        String userID = userIdField.getText();
        String password = new String(userPasswordField.getPassword());
        if (loginInfo.containsKey(userID)) {
            IDandPasswords.UserInfo userInfo = loginInfo.get(userID);
            if (userInfo.getPassword().equals(password)) {
                String fullName = userInfo.getFirstName() + " " + userInfo.getLastName();
                messageLabel.setForeground(Color.GREEN);
                messageLabel.setText("Login successful, Welcome " + fullName);
                // Instantiate WelcomePage after successful login
                WelcomePage welcomePage = new WelcomePage(userID);
                // Dispose current frame
                frame.dispose();
            } else {
                messageLabel.setForeground(Color.RED);
                messageLabel.setText("Wrong password");
            }
        } else {
            messageLabel.setForeground(Color.RED);
            messageLabel.setText("Username not found");
        }
    }

    private void reset(ActionEvent event) {
        userIdField.setText("");
        userPasswordField.setText("");
        messageLabel.setText(EMPTY);
    }

    private void showLogin(ActionEvent event) {
        cardLayout.show(cardPanel, LOGIN);
    }

    private void showRegistration(ActionEvent event) {
        cardLayout.show(cardPanel, REGISTRATION);
    }

    private void registerUser(String userID, String firstName, String lastName, String password) {
        if (userID != null && !userID.isEmpty()) {
            if (loginInfo.containsKey(userID)) {
                JOptionPane.showMessageDialog(frame, "User ID already exists!", "Registration Error", JOptionPane.ERROR_MESSAGE);
            } else {
                if (password != null && !password.isEmpty()) {
                    loginInfo.put(userID, new IDandPasswords.UserInfo(firstName, lastName, password));
                    JOptionPane.showMessageDialog(frame, "Registration successful!", "Registration", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(frame, "Password cannot be empty!", "Registration Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new LoginPage(new HashMap<>()));
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class WelcomePage {

    JFrame frame = new JFrame();
    JButton logoutButton = new JButton("Logout");
    JLabel welcomeLabel = new JLabel("Hello!");
    JButton printInfoButton = new JButton("Print Information");
    JButton UpdateInfoButton = new JButton("Update Info");
    JButton SALARYButton = new JButton("Salary");
    JButton AttendanceButton = new JButton("Attendance");


    HashMap<String, ArrayList<String>> timeRecords = new HashMap<>();
    SalaryStorage salaryStorage = new SalaryStorage();
    IDandPasswords idAndPasswords = new IDandPasswords();

    WelcomePage(String userID) {

        welcomeLabel.setBounds(0, 0, 200, 35);
        welcomeLabel.setFont(new Font(null, Font.PLAIN, 25));
        welcomeLabel.setText("Hello Welcome" + userID);

        logoutButton.setBounds(300, 300, 100, 25);
        logoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
            }
        });


        SALARYButton.setBounds(100, 100, 200, 25);
        SALARYButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Ask for work hours
                String workHoursInput = JOptionPane.showInputDialog(frame, "Enter work hours:");
                if (workHoursInput == null || workHoursInput.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "Please enter valid work hours!", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double workHours = Double.parseDouble(workHoursInput);

                // Check if there's overtime
                String overtimeHoursInput = JOptionPane.showInputDialog(frame, "Do you have overtime hours? (Enter 0 if no)");
                double overtimeHours = Double.parseDouble(overtimeHoursInput);

                // Calculate salary details
                double basicSalary = workHours * 10; // Assuming basic salary rate is $10 per hour
                double overtimePay = 0;
                if (overtimeHours > 0) {
                    overtimePay = overtimeHours * 15; // Assuming overtime rate is $15 per hour
                }

                double grossPay = basicSalary + overtimePay;
                double taxes = grossPay * 0.2; // Assuming 20% tax rate
                double netPay = grossPay - taxes;

                // Display salary details
                String message;
                if (overtimeHours > 0) {
                    message = "Regular Work Hours: " + workHours + "n"
                            + "Overtime Hours: " + overtimeHours + "n"
                            + "Gross Pay: $" + grossPay + "n"
                            + "Taxes: $" + taxes + "n"
                            + "Net Pay: $" + netPay;
                } else {
                    message = "Regular Work Hours: " + workHours + "n"
                            + "Gross Pay: $" + grossPay + "n"
                            + "Taxes: $" + taxes + "n"
                            + "Net Pay: $" + netPay;
                }
                JOptionPane.showMessageDialog(frame, message, "Salary Details", JOptionPane.INFORMATION_MESSAGE);

                // Save salary details using SalaryStorage
                salaryStorage.addSalaryInfo(userID, grossPay, taxes, netPay, overtimePay);
            }
        });
        AttendanceButton.setBounds(100, 140, 200, 25);
        AttendanceButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Show option dialog to choose between time in and time out
                String[] options = {"Time In", "Time Out"};
                int choice = JOptionPane.showOptionDialog(frame, "Choose an option:", "Time Recorder", JOptionPane.DEFAULT_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

                if (choice == 0) { // Time In
                    TimeRecorder.recordTimeIn(timeRecords, frame);
                } else if (choice == 1) { // Time Out
                    TimeRecorder.recordTimeOut(timeRecords, frame);
                } else { // User closed the dialog or clicked outside
                    System.out.println("No option selected.");
                }
            }
        });
        UpdateInfoButton.setBounds(100, 180, 200, 25);
        UpdateInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Ask for User ID
                String userID = JOptionPane.showInputDialog(frame, "Enter User ID:");
                if (userID != null && !userID.isEmpty()) {
                    // Check if the User ID exists and is valid
                    if (idAndPasswords.isValidUserId(userID)) {
                        // If User ID is valid, proceed with updating user information
                        String newFirstName = JOptionPane.showInputDialog(frame, "Enter new first name:");
                        String newLastName = JOptionPane.showInputDialog(frame, "Enter new last name:");
                        String newPassword = JOptionPane.showInputDialog(frame, "Enter new password:");
                        if (newFirstName != null && newLastName != null && newPassword != null &&
                                !newFirstName.isEmpty() && !newLastName.isEmpty() && !newPassword.isEmpty()) {
                            // Update user information
                            idAndPasswords.updateUserInfo(userID, newFirstName, newLastName, newPassword);
                            JOptionPane.showMessageDialog(frame, "User information updated successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(frame, "Please enter valid information!", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(frame, "Invalid User ID!", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(frame, "User ID cannot be empty!", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        printInfoButton.setBounds(100, 220, 200, 25); // Position and size of the new button
        printInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Create an instance of InformationPrinter to display the information

            }
        });
        frame.add(welcomeLabel);
        frame.add(logoutButton);
        frame.add(UpdateInfoButton);
        frame.add(SALARYButton);
        frame.add(AttendanceButton);
        frame.add(printInfoButton);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(420, 420);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            IDandPasswords idAndPasswords = new IDandPasswords();
            // Retrieve necessary data from WelcomePage, SalaryStorage, IDandPasswords
            HashMap<String, ArrayList<String>> timeRecords = new HashMap<>();
            SalaryStorage salaryStorage = new SalaryStorage();
            Map<String, IDandPasswords.UserInfo> loginInfo = idAndPasswords.getLoginInfo();
            // Create an instance of InformationPrinter with the extracted data

        });
    }
}
import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;

public class TimeRecorder {
    // Method to record time in
    public static void recordTimeIn(HashMap<String, ArrayList<String>> timeRecords, JFrame frame) {
        String WorkId = JOptionPane.showInputDialog(frame, "Enter WorkID:");
        if (WorkId == null || WorkId.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "WorkID cannot be empty!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String timeIn = getTimeStamp();
        timeRecords.putIfAbsent(WorkId, new ArrayList<>());
        timeRecords.get(WorkId).add(timeIn);
        JOptionPane.showMessageDialog(frame, "Time In recorded for " + WorkId + ": " + timeIn);
    }

    // Method to record time out
    public static void recordTimeOut(HashMap<String, ArrayList<String>> timeRecords, JFrame frame) {
        String WorkId = JOptionPane.showInputDialog(frame, "Enter username:");
        if (WorkId == null || WorkId.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "Username cannot be empty!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!timeRecords.containsKey(WorkId) || timeRecords.get(WorkId).isEmpty()) {
            JOptionPane.showMessageDialog(frame, "No Time In recorded for " + WorkId + "!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String timeOut = getTimeStamp();
        timeRecords.get(WorkId).add(timeOut);
        JOptionPane.showMessageDialog(frame, "Time Out recorded for " + WorkId + ": " + timeOut);
    }

    // Method to get the current time stamp
    private static String getTimeStamp() {
        return new java.util.Date().toString();
    }
}
import java.util.HashMap;

public class SalaryStorage {
    private HashMap<String, SalaryInfo> salaryMap = new HashMap<>();

    public void addSalaryInfo(String username, double grossPay, double taxes, double netPay, double overtimePay) {
        salaryMap.put(username, new SalaryInfo(grossPay, taxes, netPay, overtimePay));
    }

    public HashMap<String, SalaryInfo> getSalaryMap() {
        return salaryMap;
    }

    public static class SalaryInfo {
        private double grossPay;
        private double taxes;
        private double netPay;
        private double overtimePay;

        public SalaryInfo(double grossPay, double taxes, double netPay, double overtimePay) {
            this.grossPay = grossPay;
            this.taxes = taxes;
            this.netPay = netPay;
            this.overtimePay = overtimePay;
        }

        // Getters for salary information
        public double getGrossPay() {
            return grossPay;
        }

        public double getTaxes() {
            return taxes;
        }

        public double getNetPay() {
            return netPay;
        }

        public double getOvertimePay() {
            return overtimePay;
        }
    }
}
import java.util.HashMap;
import java.util.Map;

public class IDandPasswords {

    private HashMap<String, UserInfo> logininfo = new HashMap<>();

    public IDandPasswords() {
        // Populate logininfo
        logininfo.put("Justine", new UserInfo("Cute", "Realubit", "pizza"));
        logininfo.put("Kacey", new UserInfo("Cute", "Gutierrez", "PASSWORD"));
        logininfo.put("Joshua", new UserInfo("Cute", "Santos", "abc123"));
    }

    public boolean isValidUserId(String userId) {
        return logininfo.containsKey(userId);
    }

    // Method to update user information
    public void updateUserInfo(String userId, String newFirstName, String newLastName, String newPassword) {
        UserInfo user = logininfo.get(userId);
        if (user != null) {
            user.setFirstName(newFirstName);
            user.setLastName(newLastName);
            user.setPassword(newPassword);
        }
    }

    public Map<String, UserInfo> getLoginInfo() {
        return logininfo;
    }

    public static class UserInfo {
        private String firstName;
        private String lastName;
        private String password;

        public UserInfo(String firstName, String lastName, String password) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.password = password;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}

New contributor

vanai is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật