这个系统是当时学习Java时的大作业,因为当时没有要求使用数据库,所以数据都是通过txt来进行获取
一.需求分析
1.系统描述
《健康监测管理系统》是一个用于管理健康监测的系统。该系统采用面向对象编程语言进行开发,为管理员提供了一套完整的功能,以实现高效的健康监测服务。
该系统的主要功能包括登录、测量点信息管理、用户管理、监测管理和信息管理。
2.基本要求
这个项目的基本要求包括以下几点
1. 登录功能:管理员使用正确的用户名和密码登录系统,如果输入错误,则提示密码或账户错误。
2. 测量点信息管理:管理员可以进行增加、修改、查询和删除测量点信息的操作。
3. 用户管理:管理员可以进行增加、删除、修改和查询客户信息的操作。
4. 监测管理:管理员可以选择测量点,并为该测量点添加多个用户。
5. 信息管理:管理员可以选择测量点,计算并查看该用户的平均体温、心率等信息。
6. 数据导出存储:系统可以将数据导出为文件进行存储。
二.功能实现
1.主要的一个登陆界面HealthMonitoringAppUI.java
package Healthmonitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/*
* 这个是登陆界面,为第一个启动界面
* 启动的时候可以直接运行此页面直接运行此界面
*/
//枚举,通过读取user.txt的ADMIN,REGULAR来判断登录用户为管理员还是普通用户
enum UserType {
ADMIN,
REGULAR
}
public class HealthMonitoringAppUI extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
protected JPanel currentPanel;
private UserType currentUserType; // 用于保存当前用户类型
protected String loggedInUsername;// 用于传递主页用户名
public HealthMonitoringAppUI() {
setTitle("健康监测管理登录");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel loginPanel = createLoginPanel();
currentPanel = loginPanel;
add(loginPanel);
}
private JPanel createLoginPanel() {
JPanel loginPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 加载背景图片 (背景图片替换成自己的)
ImageIcon originalBackground = new ImageIcon(getClass().getResource("background.jpg"));
Image backgroundImg = originalBackground.getImage();
// 设置透明度
Graphics2D g2d = (Graphics2D) g.create();
float alpha = 0.5f; // 透明度值(0.0 - 1.0,值越小越透明)
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(alphaComposite);
// 绘制带透明度的背景图片
g2d.drawImage(backgroundImg, 0, 0, getWidth(), getHeight(), this);
g2d.dispose(); // 释放资源
}
};
loginPanel.setLayout(new BorderLayout());
JLabel titleLabel = new JLabel("健康监测管理登录");
titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
loginPanel.add(titleLabel, BorderLayout.NORTH);
JPanel inputPanel = new JPanel(new GridBagLayout());
inputPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;
JLabel usernameLabel = new JLabel("用户名:");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
inputPanel.add(usernameLabel, gbc);
usernameField = new JTextField(15);
usernameField.setBorder(BorderFactory.createEmptyBorder()); // 设置边框为空
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
inputPanel.add(usernameField, gbc);
JLabel passwordLabel = new JLabel("密码:");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
inputPanel.add(passwordLabel, gbc);
passwordField = new JPasswordField(15);
passwordField.setBorder(BorderFactory.createEmptyBorder()); // 设置边框为空
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
inputPanel.add(passwordField, gbc);
JButton loginButton = new JButton("登录");
loginButton.setBackground(Color.BLUE);
loginButton.setForeground(Color.WHITE);
loginButton.setBorderPainted(false); // 移除按钮边框
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);
if (validateLogin(username, password)) {
JOptionPane.showMessageDialog(null, "登录成功");
openMainPage();
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误,请重新输入", "登录失败", JOptionPane.ERROR_MESSAGE);
passwordField.setText("");
}
}
});
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.setOpaque(false);
buttonPanel.add(loginButton);
loginPanel.add(inputPanel, BorderLayout.CENTER);
loginPanel.add(buttonPanel, BorderLayout.SOUTH);
return loginPanel;
}
private boolean validateLogin(String username, String password) {
// 用户名不能包含特殊字符
if (username.matches(".*[%$^&*].*")) {
JOptionPane.showMessageDialog(null, "用户名包含非法字符,请重新输入", "登录失败", JOptionPane.ERROR_MESSAGE);
return false;
}
// 读取txt的用户信息
String filePath = "./users.txt";
// String filePath = HealthMonitoringAppUI.class.getResource("users.txt").getPath();
boolean isValid = false;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
if (parts.length == 3 && parts[0].equals(username) && parts[1].equals(password)) {
isValid = true;
loggedInUsername = username; // 登录成功后记录用户名
currentUserType = parts[2].equals("admin") ? UserType.ADMIN : UserType.REGULAR;
break;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return isValid;
}
private void openMainPage() {
getContentPane().removeAll();
if (currentUserType == UserType.ADMIN) {
setTitle("健康监测管理系统 - 管理员主页");
JPanel adminPanel = createAdminPanel();
currentPanel = adminPanel;
add(adminPanel);
String currentDirectory = System.getProperty("user.dir");
System.out.println("Current working directory: " + currentDirectory);
} else {
openUserPage();
}
revalidate();
repaint();
}
private void openUserPage() {
UserPageUI userPage = new UserPageUI();
userPage.setVisible(true);
dispose(); // 关闭当前登录界面
}
//退出登录回到登陆界面
private void openLoginPanel() {
getContentPane().removeAll();
setTitle("健康监测管理登录");
JPanel loginPanel = createLoginPanel();
currentPanel = loginPanel;
add(loginPanel);
revalidate();
repaint();
}
private JPanel createAdminPanel() {
JPanel mainPanel = new JPanel(new BorderLayout()); // 使用边界布局
// 左侧菜单栏
JPanel sideMenuPanel = new JPanel(new GridLayout(5, 1)); // 4行1列
JButton productInfoButton = new JButton("测量点信息管理");
JButton usersManagementButton = new JButton("用户管理");
JButton productSalesButton = new JButton("监测管理");
JButton orderManagementButton = new JButton("信息管理");
JButton accountManagementButton = new JButton("账号管理");
// 设置按钮背景色和前景色
productInfoButton.setBackground(Color.WHITE);
productInfoButton.setForeground(Color.BLACK);
usersManagementButton.setBackground(Color.WHITE);
usersManagementButton.setForeground(Color.BLACK);
productSalesButton.setBackground(Color.WHITE);
productSalesButton.setForeground(Color.BLACK);
orderManagementButton.setBackground(Color.WHITE);
orderManagementButton.setForeground(Color.BLACK);
accountManagementButton.setBackground(Color.WHITE);
accountManagementButton.setForeground(Color.BLACK);
// 添加按钮边框
productInfoButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
usersManagementButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
productSalesButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
orderManagementButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
accountManagementButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// 将按钮添加到左侧菜单栏
sideMenuPanel.add(accountManagementButton);
sideMenuPanel.add(usersManagementButton);
sideMenuPanel.add(productInfoButton);
sideMenuPanel.add(productSalesButton);
sideMenuPanel.add(orderManagementButton);
// 顶部面板
JPanel topPanel = new JPanel(new BorderLayout());
// 顶部右上角菜单栏
JPanel topRightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JLabel currentUserLabel = new JLabel("当前用户:" + loggedInUsername); // 显示登录成功的用户名
JButton logoutButton = new JButton("退出登录");
// 显示当前时间
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
JLabel timeLabel = new JLabel(dtf.format(LocalDateTime.now()));
// 退出登录按钮的点击事件
logoutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 关闭当前窗口,打开登录页面等
JOptionPane.showMessageDialog(null, "退出登录成功");
loggedInUsername = null; // 清除已登录的用户名
dispose(); // 关闭当前窗口
HealthMonitoringAppUI newApp = new HealthMonitoringAppUI(); // 创建一个新的应用实例
newApp.setVisible(true); // 显示登录界面
}
});
// 更新时间的定时任务
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timeLabel.setText(dtf.format(LocalDateTime.now()));
}
});
timer.start(); // 启动定时器
// 将当前用户和退出登录按钮添加到顶部右上角面板
topRightPanel.add(currentUserLabel);
topRightPanel.add(logoutButton);
topPanel.add(topRightPanel, BorderLayout.NORTH);
// 底部右下角显示当前时间
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(timeLabel);
// 将左侧菜单栏、顶部和底部面板添加到主面板中
mainPanel.add(sideMenuPanel, BorderLayout.WEST);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
JPanel centerPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 加载原始图像
ImageIcon originalBackground = new ImageIcon(getClass().getResource("logo.jpg"));
Image backgroundImg = originalBackground.getImage();
// 调整图像大小
int newWidth = 1000; // 设置新的宽度
int newHeight = 1010; // 设置新的高度
Image resizedImage = backgroundImg.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// 创建一个新的 ImageIcon,使用调整大小后的图像
ImageIcon resizedBackground = new ImageIcon(resizedImage);
// 绘制带透明度的背景图片
Graphics2D g2d = (Graphics2D) g.create();
float alpha = 0.5f; // 透明度值(0.0 - 1.0,值越小越透明)
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(alphaComposite);
g2d.drawImage(resizedBackground.getImage(), 0, 0, getWidth(), getHeight(), this);
g2d.dispose(); // 释放资源
}
};
centerPanel.setLayout(new BorderLayout());
// 创建按钮用于导出所有数据
JButton exportDataButton = new JButton("导出所有数据");
exportDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exportAllData(); // 调用导出所有数据的方法
}
});
// 将导出数据的按钮添加到中间面板的南部(底部)
centerPanel.add(exportDataButton, BorderLayout.SOUTH);
// 将中间面板添加到主面板的中间
mainPanel.add(centerPanel, BorderLayout.CENTER);
// 监听器:点击按钮时触发相应的操作
// 在对应按钮的 ActionListener 中添加打开新窗口的逻辑
accountManagementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 创建并显示账号管理界面
AccountManagementUI accountManagementUI = new AccountManagementUI();
accountManagementUI.setVisible(true);
}
});
productInfoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MeasurementInfoManagementUI measurementInfoManagementUI = new MeasurementInfoManagementUI();
measurementInfoManagementUI.setVisible(true);
}
});
productSalesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MonitoringManagementUI monitoringManagementUI = new MonitoringManagementUI();
monitoringManagementUI.setVisible(true);
}
});
usersManagementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UserManagementUI userManagementUI = new UserManagementUI();
userManagementUI.setVisible(true);
}
});
orderManagementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
InformationManagementUI informationManagementUI = new InformationManagementUI();
informationManagementUI.setVisible(true);
}
});
return mainPanel;
}
private void exportAllData() {
String[] fileNames = {
"assigned_measurements.txt",
"exported_accounts.txt",
"exported_data.txt",
"measurement_points.txt",
"user_measurement_values.txt",
"users.txt"
};
String outputFileName = "所有数据.txt";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String currentTime = "当前时间:" + dtf.format(now);
try (FileWriter writer = new FileWriter(outputFileName)) {
writer.write("所有数据\n");
writer.write(currentTime + "\n");
for (String fileName : fileNames) {
writer.write("-------- " + fileName + " --------\n");
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
writer.write(line + "\n");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
JOptionPane.showMessageDialog(null, "数据成功导出到 " + outputFileName);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "数据导出失败", "错误", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
HealthMonitoringAppUI app = new HealthMonitoringAppUI();
app.setVisible(true);
});
}
}
2.信息管理的界面和功能实现 InformationManagementUI.java
package Healthmonitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.util.List;
public class InformationManagementUI extends JFrame {
private JTextArea resultTextArea;
private static final String FILE_PATH = "user_measurement_values.txt";
private static final String EXPORT_FILE_PATH = "exported_data.txt"; // 新的文本文件路径
public InformationManagementUI() {
setTitle("信息管理");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
resultTextArea = new JTextArea(10, 30);
resultTextArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(resultTextArea);
JButton calculateAverageButton = new JButton("计算平均值");
calculateAverageButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calculateAverages();
}
});
JButton exportDataButton = new JButton("导出数据"); // 导出数据按钮
exportDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exportDataToFile();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(calculateAverageButton);
buttonPanel.add(exportDataButton); // 添加导出数据按钮
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void calculateAverages() {
try {
Map<String, Map<String, List<Double>>> userMeasurements = loadUserMeasurements(FILE_PATH);
if (userMeasurements.isEmpty()) {
resultTextArea.setText("未找到用户测量数据");
return;
}
StringBuilder result = new StringBuilder();
for (Map.Entry<String, Map<String, List<Double>>> userEntry : userMeasurements.entrySet()) {
String username = userEntry.getKey();
Map<String, List<Double>> measurementsMap = userEntry.getValue();
result.append("用户: ").append(username).append("\n");
if (measurementsMap.isEmpty()) {
result.append("未找到有效测量值\n\n");
continue;
}
for (Map.Entry<String, List<Double>> entry : measurementsMap.entrySet()) {
String measurementName = entry.getKey();
List<Double> values = entry.getValue();
if (!values.isEmpty()) {
double average = values.stream().mapToDouble(Double::doubleValue).average().orElse(0);
result.append(measurementName).append(" 平均值: ").append(String.format("%.2f", average)).append("\n");
} else {
result.append(measurementName).append(" 未找到有效测量值\n");
}
}
result.append("\n");
}
resultTextArea.setText(result.toString());
} catch (FileNotFoundException e) {
resultTextArea.setText("文件未找到: " + FILE_PATH);
} catch (NumberFormatException e) {
resultTextArea.setText("数据格式错误");
} catch (Exception e) {
e.printStackTrace();
}
}
private Map<String, Map<String, List<Double>>> loadUserMeasurements(String filePath) throws FileNotFoundException {
Map<String, Map<String, List<Double>>> userMeasurements = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("处理行数据: " + line); // 输出每行被处理的数据
String[] parts = line.trim().split(": ", 2);
if (parts.length == 2) {
String username = parts[0];
String[] measurements = parts[1].split("\\s+");
Map<String, List<Double>> measurementMap = new HashMap<>();
for (int i = 0; i < measurements.length; i += 2) {
String measurementName = measurements[i].trim();
if (i + 1 < measurements.length) {
try {
double measurementValue = Double.parseDouble(measurements[i + 1].trim());
measurementMap.computeIfAbsent(measurementName, k -> new ArrayList<>()).add(measurementValue);
} catch (NumberFormatException ignored) {
// Ignore invalid measurement values
}
}
}
if (!measurementMap.isEmpty()) {
userMeasurements.put(username, measurementMap);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 输出解析后的数据到控制台
for (Map.Entry<String, Map<String, List<Double>>> entry : userMeasurements.entrySet()) {
System.out.println("用户: " + entry.getKey());
for (Map.Entry<String, List<Double>> innerEntry : entry.getValue().entrySet()) {
System.out.println("测量项: " + innerEntry.getKey() + ", 值: " + innerEntry.getValue());
}
}
return userMeasurements;
}
private void exportDataToFile() {
try (PrintWriter writer = new PrintWriter(EXPORT_FILE_PATH)) {
Map<String, Map<String, List<Double>>> userMeasurements = loadUserMeasurements(FILE_PATH);
if (userMeasurements.isEmpty()) {
writer.println("未找到用户测量数据");
return;
}
for (Map.Entry<String, Map<String, List<Double>>> entry : userMeasurements.entrySet()) {
writer.println("用户: " + entry.getKey());
for (Map.Entry<String, List<Double>> innerEntry : entry.getValue().entrySet()) {
writer.println("测量项: " + innerEntry.getKey() + ", 值: " + innerEntry.getValue());
}
writer.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
InformationManagementUI app = new InformationManagementUI();
app.setVisible(true);
});
}
}
3.账号管理界面和功能 AccountManagementUI.java
package Healthmonitoring;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class AccountManagementUI extends JFrame {
private JTable accountTable;
private DefaultTableModel tableModel;
private JButton addAccountButton;
private JButton deleteAccountButton;
private JButton editAccountButton;
private JButton exportAccountsButton;
public AccountManagementUI() {
setTitle("账号管理");
setSize(500, 300);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
String[] columns = {"用户名", "密码", "用户类型"};
tableModel = new DefaultTableModel(columns, 0);
accountTable = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(accountTable);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
addAccountButton = new JButton("增加账号");
deleteAccountButton = new JButton("删除账号");
editAccountButton = new JButton("修改账号信息");
exportAccountsButton = new JButton("导出用户信息");
buttonPanel.add(addAccountButton);
buttonPanel.add(deleteAccountButton);
buttonPanel.add(editAccountButton);
buttonPanel.add(exportAccountsButton);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
addAccountButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newAccount = JOptionPane.showInputDialog(null, "请输入新账号信息(格式:用户名 密码 用户类型):", "增加账号", JOptionPane.PLAIN_MESSAGE);
if (newAccount != null && !newAccount.isEmpty()) {
try {
Files.write(Paths.get("users.txt"), (newAccount + "\n").getBytes(), StandardOpenOption.APPEND);
updateAccountList();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "添加账号失败", "错误", JOptionPane.ERROR_MESSAGE);
}
}
}
});
deleteAccountButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRowIndex = accountTable.getSelectedRow();
if (selectedRowIndex != -1) {
try {
List<String> fileContent = new ArrayList<>(Files.readAllLines(Paths.get("users.txt")));
fileContent.remove(selectedRowIndex);
Files.write(Paths.get("users.txt"), fileContent);
updateAccountList();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "删除账号失败", "错误", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "请先选择要删除的账号", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
});
editAccountButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRowIndex = accountTable.getSelectedRow();
if (selectedRowIndex != -1) {
String username = tableModel.getValueAt(selectedRowIndex, 0).toString();
String password = tableModel.getValueAt(selectedRowIndex, 1).toString();
String userType = tableModel.getValueAt(selectedRowIndex, 2).toString();
String newAccountInfo = JOptionPane.showInputDialog(null,
"请输入新账号信息(格式:用户名 密码 用户类型):", "修改账号信息", JOptionPane.PLAIN_MESSAGE);
if (newAccountInfo != null && !newAccountInfo.isEmpty()) {
try {
List<String> fileContent = new ArrayList<>(Files.readAllLines(Paths.get("users.txt")));
fileContent.set(selectedRowIndex, newAccountInfo);
Files.write(Paths.get("users.txt"), fileContent);
updateAccountList();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "修改账号信息失败", "错误", JOptionPane.ERROR_MESSAGE);
}
}
} else {
JOptionPane.showMessageDialog(null, "请先选择要修改的账号", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
});
exportAccountsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String exportTime = dtf.format(LocalDateTime.now());
FileWriter writer = new FileWriter("exported_accounts.txt");
writer.write("用户信息\n");
for (int i = 0; i < tableModel.getRowCount(); i++) {
for (int j = 0; j < tableModel.getColumnCount(); j++) {
writer.write(tableModel.getValueAt(i, j).toString());
writer.write(j == tableModel.getColumnCount() - 1 ? "\n" : " ");
}
}
writer.write("导出时间: " + exportTime);
writer.close();
JOptionPane.showMessageDialog(null, "用户信息导出成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "用户信息导出失败", "错误", JOptionPane.ERROR_MESSAGE);
}
}
});
updateAccountList();
}
private void updateAccountList() {
try (BufferedReader br = new BufferedReader(new FileReader("users.txt"))) {
String line;
tableModel.setRowCount(0);
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
tableModel.addRow(parts);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
AccountManagementUI accountManagementUI = new AccountManagementUI();
accountManagementUI.setVisible(true);
});
}
}
4.测量点信息管理界面的实现和功能实现 MeasurementInfoManagementUI.java
package Healthmonitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class MeasurementInfoManagementUI extends JFrame {
private JTextArea measurementTextArea;
public MeasurementInfoManagementUI() {
setTitle("测量点信息管理");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
measurementTextArea = new JTextArea(15, 30);
measurementTextArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(measurementTextArea);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton loadButton = new JButton("加载测量点");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadMeasurementPoints();
}
});
JButton addButton = new JButton("添加测量点");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addMeasurementPoint();
}
});
JButton deleteButton = new JButton("删除测量点");
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteMeasurementPoint();
}
});
buttonPanel.add(loadButton);
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void loadMeasurementPoints() {
String filePath = "./measurement_points.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
measurementTextArea.setText(sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void addMeasurementPoint() {
String newMeasurement = JOptionPane.showInputDialog(null, "请输入新的测量点信息:", "添加测量点", JOptionPane.PLAIN_MESSAGE);
if (newMeasurement != null && !newMeasurement.isEmpty()) {
try (FileWriter fw = new FileWriter("./measurement_points.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)) {
pw.println(newMeasurement);
pw.flush();
loadMeasurementPoints(); // 重新加载显示测量点信息
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法添加测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
}
private void deleteMeasurementPoint() {
String selectedMeasurement = measurementTextArea.getSelectedText();
if (selectedMeasurement != null && !selectedMeasurement.isEmpty()) {
String text = measurementTextArea.getText().replace(selectedMeasurement, "").trim();
measurementTextArea.setText(text);
try {
File inputFile = new File("./measurement_points.txt");
File tempFile = new File("./temp_measurement_points.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = selectedMeasurement;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
if (currentLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
if (!inputFile.delete()) {
JOptionPane.showMessageDialog(null, "无法删除测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
if (!tempFile.renameTo(inputFile)) {
JOptionPane.showMessageDialog(null, "无法删除测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法删除测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "请选择要删除的测量点信息", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MeasurementInfoManagementUI measurementUI = new MeasurementInfoManagementUI();
measurementUI.setVisible(true);
});
}
}
5.监测管理界面的实现和功能实现 MonitoringManagementUI.java
package Healthmonitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MonitoringManagementUI extends JFrame {
private JList<String> measurementList;
private JList<String> usersList;
private JTextArea assignedMeasurementsTextArea;
public MonitoringManagementUI() {
setTitle("监测管理");
setSize(800, 400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new GridLayout(1, 3));
JPanel measurementPanel = new JPanel(new BorderLayout());
JPanel usersPanel = new JPanel(new BorderLayout());
JPanel bottomPanel = new JPanel(new BorderLayout());
measurementList = new JList<>();
usersList = new JList<>();
measurementList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
usersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
assignedMeasurementsTextArea = new JTextArea(15, 20);
assignedMeasurementsTextArea.setEditable(false);
JScrollPane assignedMeasurementsScrollPane = new JScrollPane(assignedMeasurementsTextArea);
JPanel buttonPanel = new JPanel(new GridLayout(5, 1, 5, 5)); // 调整按钮面板的行列数和间距
JButton loadMeasurementButton = new JButton("加载测量点");
loadMeasurementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadMeasurementPoints();
}
});
JButton loadUsersButton = new JButton("加载用户");
loadUsersButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadUsers();
}
});
JButton assignUserButton = new JButton("分配用户");
assignUserButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
assignUserToMeasurement();
}
});
JButton loadAssignedMeasurementsButton = new JButton("加载分配信息");
loadAssignedMeasurementsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadAssignedMeasurements();
}
});
JButton deleteAssignedMeasurementButton = new JButton("删除分配信息");
deleteAssignedMeasurementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteAssignedMeasurement();
}
});
buttonPanel.add(loadMeasurementButton);
buttonPanel.add(loadUsersButton);
buttonPanel.add(assignUserButton);
buttonPanel.add(loadAssignedMeasurementsButton);
buttonPanel.add(deleteAssignedMeasurementButton);
measurementPanel.add(new JLabel("测量点列表"), BorderLayout.NORTH);
measurementPanel.add(new JScrollPane(measurementList), BorderLayout.CENTER);
usersPanel.add(new JLabel("普通用户列表"), BorderLayout.NORTH);
usersPanel.add(new JScrollPane(usersList), BorderLayout.CENTER);
bottomPanel.add(new JLabel("已分配的测量点信息"), BorderLayout.NORTH);
bottomPanel.add(assignedMeasurementsScrollPane, BorderLayout.CENTER);
bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(measurementPanel);
mainPanel.add(usersPanel);
mainPanel.add(bottomPanel);
add(mainPanel);
}
private void loadMeasurementPoints() {
DefaultListModel<String> model = new DefaultListModel<>();
String filePath = "./measurement_points.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
model.addElement(line);
}
measurementList.setModel(model);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载测量点信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void loadUsers() {
DefaultListModel<String> model = new DefaultListModel<>();
String filePath = "./users.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] userInfo = line.split(" ");
if (userInfo.length >= 3 && userInfo[2].equals("regular")) {
model.addElement(userInfo[0]);
}
}
usersList.setModel(model);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载用户信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void assignUserToMeasurement() {
String selectedMeasurement = measurementList.getSelectedValue();
String selectedUser = usersList.getSelectedValue();
if (selectedMeasurement != null && selectedUser != null) {
try (FileWriter fw = new FileWriter("./assigned_measurements.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)) {
pw.println(selectedUser + " - " + selectedMeasurement);
pw.flush();
JOptionPane.showMessageDialog(null, "成功为用户分配测量点", "成功", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法为用户分配测量点", "错误", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "请选择用户和测量点", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
private void loadAssignedMeasurements() {
assignedMeasurementsTextArea.setText(""); // 清空文本区域
String filePath = "./assigned_measurements.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
assignedMeasurementsTextArea.append(line + "\n");
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载分配信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void deleteAssignedMeasurement() {
String selectedText = assignedMeasurementsTextArea.getSelectedText();
if (selectedText != null && !selectedText.isEmpty()) {
String filePath = "./assigned_measurements.txt";
File file = new File(filePath);
StringBuilder content = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(selectedText)) {
content.append(line).append("\n");
}
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法读取分配信息", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
try (FileWriter fw = new FileWriter(filePath)) {
fw.write(content.toString().trim());
JOptionPane.showMessageDialog(null, "成功删除分配信息", "成功", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法删除分配信息", "错误", JOptionPane.ERROR_MESSAGE);
}
assignedMeasurementsTextArea.setText(content.toString());
} else {
JOptionPane.showMessageDialog(null, "请选择要删除的分配信息", "提示", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MonitoringManagementUI monitoringUI = new MonitoringManagementUI();
monitoringUI.setVisible(true);
});
}
}
6.用户管理界面的实现和功能实现 UserManagementUI.java
package Healthmonitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
public class UserManagementUI extends JFrame {
private JComboBox<String> userComboBox;
private JTextArea measurementValueTextArea;
private JButton saveButton;
private JButton viewDataButton;
private JButton modifyDataButton;
private JButton deleteDataButton;
private Map<String, List<String>> assignedMeasurementsMap;
public UserManagementUI() {
setTitle("用户管理");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
assignedMeasurementsMap = new HashMap<>();
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel userLabel = new JLabel("选择用户:");
userComboBox = new JComboBox<>();
loadAssignedUsers();
userComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedUser = Objects.requireNonNull(userComboBox.getSelectedItem()).toString();
viewMeasurementData(selectedUser);
}
});
inputPanel.add(userLabel);
inputPanel.add(userComboBox);
mainPanel.add(inputPanel, BorderLayout.NORTH);
measurementValueTextArea = new JTextArea(10, 30);
measurementValueTextArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(measurementValueTextArea);
JPanel buttonPanel = new JPanel(new FlowLayout());
saveButton = new JButton("保存数据");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedUser = Objects.requireNonNull(userComboBox.getSelectedItem()).toString();
saveMeasurementValue(selectedUser);
}
});
viewDataButton = new JButton("查看数据");
viewDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedUser = Objects.requireNonNull(userComboBox.getSelectedItem()).toString();
viewMeasurementData(selectedUser);
}
});
modifyDataButton = new JButton("修改数据");
modifyDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedUser = Objects.requireNonNull(userComboBox.getSelectedItem()).toString();
modifyMeasurementData(selectedUser);
}
});
deleteDataButton = new JButton("删除数据");
deleteDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedUser = Objects.requireNonNull(userComboBox.getSelectedItem()).toString();
deleteMeasurementData(selectedUser);
}
});
buttonPanel.add(saveButton);
buttonPanel.add(viewDataButton);
buttonPanel.add(modifyDataButton);
buttonPanel.add(deleteDataButton);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void loadAssignedUsers() {
String filePath = "./assigned_measurements.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" - ");
assignedMeasurementsMap.putIfAbsent(parts[0], new ArrayList<>());
List<String> measurements = assignedMeasurementsMap.get(parts[0]);
measurements.add(parts[1]);
assignedMeasurementsMap.put(parts[0], measurements);
}
for (String user : assignedMeasurementsMap.keySet()) {
userComboBox.addItem(user);
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载分配用户信息", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void viewMeasurementData(String selectedUser) {
if (selectedUser != null && !selectedUser.isEmpty()) {
String filePath = "./user_measurement_values.txt";
StringBuilder userData = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith(selectedUser + ":")) {
userData.append(line).append("\n");
}
}
if (userData.length() == 0) {
userData.append("未找到该用户的数据");
}
measurementValueTextArea.setText(userData.toString());
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载用户测量数据", "错误", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveMeasurementValue(String selectedUser) {
List<String> assignedMeasurements = assignedMeasurementsMap.get(selectedUser);
if (selectedUser != null && !selectedUser.isEmpty() && assignedMeasurements != null && !assignedMeasurements.isEmpty()) {
StringBuilder inputValues = new StringBuilder();
for (String measurement : assignedMeasurements) {
String inputValue = JOptionPane.showInputDialog(null, "请输入" + selectedUser + "的" + measurement + "值:");
if (inputValue != null && !inputValue.isEmpty()) {
inputValues.append(measurement).append(": ").append(inputValue).append(" ");
} else {
JOptionPane.showMessageDialog(null, "请输入" + measurement + "值", "提示", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
if (inputValues.length() > 0) {
String dataToSave = selectedUser + ": " + inputValues.toString().replaceAll(" $", "");
String filePath = "./user_measurement_values.txt";
try (FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)) {
pw.println(dataToSave);
pw.flush();
JOptionPane.showMessageDialog(null, "成功保存用户测量数据", "成功", JOptionPane.INFORMATION_MESSAGE);
viewMeasurementData(selectedUser);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法保存用户测量数据", "错误", JOptionPane.ERROR_MESSAGE);
}
}
} else {
JOptionPane.showMessageDialog(null, "找不到分配给该用户的测量数据", "错误", JOptionPane.ERROR_MESSAGE);
}
}
private void modifyMeasurementData(String selectedUser) {
String data = measurementValueTextArea.getText();
String newValue = JOptionPane.showInputDialog(null, "请输入新的数据:", "修改数据", JOptionPane.PLAIN_MESSAGE);
if (newValue != null && !newValue.isEmpty()) {
String[] lines = data.split("\n");
StringBuilder modifiedData = new StringBuilder();
boolean modified = false;
for (String line : lines) {
if (line.startsWith(selectedUser + ":")) {
modifiedData.append(newValue).append("\n");
modified = true;
} else {
modifiedData.append(line).append("\n");
}
}
if (!modified) {
JOptionPane.showMessageDialog(null, "未找到该用户的数据", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
measurementValueTextArea.setText(modifiedData.toString().trim());
JOptionPane.showMessageDialog(null, "已修改数据", "成功", JOptionPane.INFORMATION_MESSAGE);
}
}
private void deleteMeasurementData(String selectedUser) {
String filePath = "./user_measurement_values.txt";
List<String> remainingData = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.startsWith(selectedUser + ":")) {
remainingData.add(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载用户测量数据", "错误", JOptionPane.ERROR_MESSAGE);
}
try (FileWriter fw = new FileWriter(filePath);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)) {
for (String line : remainingData) {
pw.println(line);
}
JOptionPane.showMessageDialog(null, "已删除 " + selectedUser + " 的数据", "成功", JOptionPane.INFORMATION_MESSAGE);
viewMeasurementData(selectedUser);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "无法保存用户测量数据", "错误", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
UserManagementUI app = new UserManagementUI();
app.setVisible(true);
});
}
}
7.需要的txt文件
这个程序比较简单,主要是满足大作业的要求,主要都是一些基础功能的使用。这些代码感觉适合刚开始学习Java的人,可以了解到类和对象的使用、继承的使用、还有一些文件读取的功能学习。