我尝试访问我的哈希映射类,以便检索我从哈希映射类中输入的数据。这是我用于访问哈希图的更新按钮。
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");
JButton leaveManagementButton = new JButton("Leave Management");
HashMap<String, ArrayList<String>> timeRecords = new HashMap<>();
SalaryStorage salaryStorage = new SalaryStorage();
IDandPasswords idAndPasswords = new IDandPasswords();
HashMap<String, ArrayList<Leave>> leaveRecords = new HashMap<>();
WelcomePage(String userID) {
welcomeLabel.setBounds(0, 0, 200, 35);
welcomeLabel.setFont(new Font(null, Font.PLAIN, 25));
welcomeLabel.setText("Hello " +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 * 400; // Assuming basic salary rate is $10 per hour
double overtimePay = 0;
if (overtimeHours > 0) {
overtimePay = overtimeHours * 600; // Assuming overtime rate is $15 per hour
}
double grossPay = basicSalary + overtimePay;
double taxes = grossPay * 0.14 * 0.04 * 4.5; // 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) {
StringBuilder infoBuilder = new StringBuilder();
// Append user information
IDandPasswords.UserInfo userInfo = idAndPasswords.getLoginInfo().get(userID);
if (userInfo != null) {
infoBuilder.append("User Information:\n");
infoBuilder.append("User ID: ").append(userID).append("\n");
infoBuilder.append("First Name: ").append(userInfo.getFirstName()).append("\n");
infoBuilder.append("Last Name: ").append(userInfo.getLastName()).append("\n");
// Append salary information
SalaryStorage.SalaryInfo salaryInfo = salaryStorage.getSalaryMap().get(userID);
if (salaryInfo != null) {
infoBuilder.append("\nSalary Information:\n");
infoBuilder.append("Gross Pay: $").append(salaryInfo.getGrossPay()).append("\n");
infoBuilder.append("Taxes: $").append(salaryInfo.getTaxes()).append("\n");
infoBuilder.append("Net Pay: $").append(salaryInfo.getNetPay()).append("\n");
infoBuilder.append("Overtime Pay: $").append(salaryInfo.getOvertimePay()).append("\n");
}
// Append time records
if (timeRecords.containsKey(userID)) {
ArrayList<String> records = timeRecords.get(userID);
infoBuilder.append("\nTime Records:\n");
for (String record : records) {
infoBuilder.append(record).append("\n");
}
}
} else {
// Handle case where user ID doesn't exist
JOptionPane.showMessageDialog(frame, "User ID not found!", "Error", JOptionPane.ERROR_MESSAGE);
}
// Print the information
JOptionPane.showMessageDialog(frame, infoBuilder.toString(), "User Information", JOptionPane.INFORMATION_MESSAGE);
}
});
leaveManagementButton.setBounds(100, 260, 200, 25); // Position and size of the new button
leaveManagementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String[] options = {"Maternal Leave", "Sick Leave", "Vacation Leave"};
String selectedOption = (String) JOptionPane.showInputDialog(frame, "Choose a leave type:",
"Leave Management", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (selectedOption != null) {
int maxLeaves = 10; // Example maximum limit of leaves
String leaveDaysInput = JOptionPane.showInputDialog(frame, "Enter number of days for " + selectedOption + " (max " + maxLeaves + " days):");
if (leaveDaysInput != null && !leaveDaysInput.isEmpty()) {
int leaveDays = Integer.parseInt(leaveDaysInput);
if (leaveDays > 0 && leaveDays <= maxLeaves) {
// Logic to handle leave request
JOptionPane.showMessageDialog(frame, "Leave requested successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame, "Invalid number of days or exceeds maximum limit!", "Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(frame, "Please enter valid number of days!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
});
frame.add(welcomeLabel);
frame.add(logoutButton);
frame.add(UpdateInfoButton);
frame.add(SALARYButton);
frame.add(AttendanceButton);
frame.add(printInfoButton);
frame.add(leaveManagementButton);
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
});
}
}
每当我尝试单击该按钮时,它都会提示我找不到用户名,但是每当我尝试输入从哈希图中输入的人口时,它都会引导我打印我输入的信息。我认为我的哈希图不是不会被覆盖。这是我的 ID、名字、姓氏和密码的哈希图代码。
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);
} else {
System.out.println("User not found!");
}
}
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;
}
}
}
在我的登录页面
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()) {
// Replace the hardcoded values with the entered data
loginInfo.put(userID, new IDandPasswords.UserInfo(firstName, lastName, password));
JOptionPane.showMessageDialog(frame, "Registration successful!", "Register", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame, "Password cannot be empty!", "Registration Error", JOptionPane.ERROR_MESSAGE);
}
}
}
} ```
您在类
IDandPasswords
中创建类 WelcomePage
的实例:
IDandPasswords idAndPasswords = new IDandPasswords();
您在
IDandPasswords
中更新了类 LogIn Page
的实例。 (我认为 LogIn Page
是另一个类。)
loginInfo.put(userID, new IDandPasswords.UserInfo(firstName, lastName, password));
我还假设
loginInfo
是 IDandPasswords
的实例。
因此,类
idAndPasswords
中的变量 WelcomePage
不是 指的是变量 loginInfo
所指的同一个实例,这就是为什么您永远不会在 idAndPasswords
中找到您在 loginInfo
中更新的详细信息。
您需要将
loginInfo
传递到班级WelcomePage
。如果您从类 WelcomePage
创建 LogIn Page
的实例,则可以向 WelcomePage
的构造函数添加一个参数,例如
WelcomePage(String userID, IDandPasswords idAndPasswords) {
this.idAndPasswords = idAndPasswords;
}
或者,可以将类
IDandPasswords
设为 singleton 或将该类的 logininfo
属性设为静态,然后将方法设为静态。import java.util.HashMap;
import java.util.Map;
public class IDandPasswords {
private static Map<String, UserInfo> logininfo = new HashMap<>();
static {
// 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 static boolean isValidUserId(String userId) {
return logininfo.containsKey(userId);
}
// Method to update user information
public static 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);
} else {
System.out.println("User not found!");
}
}
public static 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;
}
}
}
那么您将始终访问和修改同一个
IDandPasswords
对象。