35.JLabel、JTextField、JPasswordField、JTextArea、JPanel、setBorder

本文介绍了Java中GUI组件如JLabel、JTextField、JPasswordField、JTextArea等的基本使用,并展示了如何通过GridLayout进行布局管理。

类 JLabel 用于短文本字符串或图像或二者的显示区。

JLabel jLable = new JLabel("JLab组件",JLabel.CENTER);

类 JTextField JTextField 是一个轻量级组件,它允许编辑单行文本。

JFrame jFrame = new JFrame("JLable测试");
jFrame.setLayout(new GridLayout(1, 2, 5, 5));
JLabel jLable = new JLabel("用户名:",JLabel.CENTER);
JTextField jtf = new JTextField();//文本框,可输入文字

输出 这里写图片描述


类 JPasswordField 是一个轻量级组件,允许编辑单行文本,其视图指示键入内容,但不显示原始字符

        jFrame.setLayout(new GridLayout(2, 2, 5, 5));
        JLabel jLable = new JLabel("用户名:",JLabel.CENTER);
        JTextField jtf = new JTextField();//文本框,可输入文字
        JLabel jLable1 = new JLabel("密码:",JLabel.CENTER);
        JPasswordField jpf = new JPasswordField();//密码框

输出 这里写图片描述


类 JTextArea 是一个显示纯文本的多行区域。

JTextArea jta = new JTextArea("请输入用户名");//文本域,可多行输入

类 JPanel 是一般轻量级容器。可通过jFrame.add(jPanel)添加到jFrame上;与JFrame一样也是容器。容器上面可以加容器。

public static void main(String[] args) {
        JFrame jFrame = new JFrame("JPanel面板测试");
        JPanel jPanel = new JPanel();
        jFrame.add(jPanel);
        jPanel.setLayout(new GridLayout(3, 2, 5, 5));
        JLabel jLable = new JLabel("用户名:");
        JTextArea jta = new JTextArea();//多行文本框,可输入文字
        JLabel jLable1 = new JLabel("密码:");
        JPasswordField jpf = new JPasswordField();//密码框
        JButton jb1 = new JButton("登陆");
        JButton jb2 = new JButton("注册");
        jPanel.add(jLable);
        jPanel.add(jta);
        jPanel.add(jLable1);
        jPanel.add(jpf);
        jPanel.add(jb1);
        jPanel.add(jb2);
        jFrame.setLocation(400, 100);//设置容器位置
    //  Container c = jFrame.getContentPane();
    //  c.setBackground(Color.DARK_GRAY);
        jFrame.setSize(300, 120);//设置容器大小
        jFrame.setVisible(true);//让容器显示
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

输出 这里写图片描述

setBorder方法
public void setBorder(Border border)
设置此组件的边框。

类 EmptyBorder

public EmptyBorder(int top,
                   int left,
                   int bottom,
                   int right)创建具有指定 insets 的空边框 

参数:
top - 边框顶部 inset
left - 边框左部 inset
bottom - 边框底部 inset
right - 边框右部 inset
jPanel.setBorder(new EmptyBorder(10, 10, 10, 10));//设置边距,实质是设置了一个空边框EmptyBorder。

设置边距后输出 这里写图片描述

package ManagementSystem001; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.*; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.List; // 会员等级枚举 enum MembershipLevel { DIAMOND(0.77, "钻石卡"), PLATINUM(0.83, "白金卡"), GOLD(0.88, "黄金卡"), SILVER(0.9, "白银卡"); private final double discount; private final String name; MembershipLevel(double discount, String name) { this.discount = discount; this.name = name; } public double getDiscount() { return discount; } public String getName() { return name; } } // 交易类型和消费类型枚举 enum TransactionType { RECHARGE("充值"), PAYMENT("消费"); private final String displayName; TransactionType(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } } enum ConsumptionType { HAIR_CARE("头发护理"), SHOPPING("商场购物"), FRESH_FOOD("生鲜食品"); private final String name; ConsumptionType(String name) { this.name = name; } public String getName() { return name; } } // 交易记录类 class TransactionRecord { private LocalDate date; private double amount; private TransactionType type; private ConsumptionType category; public TransactionRecord(LocalDate date, double amount, TransactionType type, ConsumptionType category) { this.date = date; this.amount = amount; this.type = type; this.category = category; } public LocalDate getDate() { return date; } public double getAmount() { return amount; } public TransactionType getType() { return type; } public ConsumptionType getCategory() { return category; } } // 会员类 class Member { private String cardNumber; private String name; private String gender; private int age; private String occupation; private String phone; private String idNumber; private double balance; private LocalDate registrationDate; private MembershipLevel level; private List<TransactionRecord> transactionHistory; private double accumulatedExpense; public Member(String cardNumber, String name, String gender, int age, String occupation, String phone, String idNumber) { this.cardNumber = cardNumber; this.name = name; this.gender = gender; this.age = age; this.occupation = occupation; this.phone = phone; this.idNumber = idNumber; this.balance = 0; this.registrationDate = LocalDate.now(); this.level = MembershipLevel.SILVER; this.transactionHistory = new ArrayList<>(); this.accumulatedExpense = 0; } // 会员卡升级逻辑 public void checkMembershipUpgrade() { LocalDate now = LocalDate.now(); long daysSinceRegistration = ChronoUnit.DAYS.between(registrationDate, now); if (level == MembershipLevel.SILVER && daysSinceRegistration >= 180) { level = MembershipLevel.GOLD; } else if (level == MembershipLevel.GOLD && accumulatedExpense >= 1288) { level = MembershipLevel.PLATINUM; } else if (level == MembershipLevel.PLATINUM && accumulatedExpense >= 5888) { level = MembershipLevel.DIAMOND; } } // 充值余额 public boolean recharge(double amount, String authCode) { if (verifyAuthCode(authCode)) { balance += amount; transactionHistory.add(new TransactionRecord( LocalDate.now(), amount, TransactionType.RECHARGE, null)); return true; } return false; } // 消费扣款 public boolean deduct(double amount, String authCode, ConsumptionType category) { if (!verifyAuthCode(authCode)) return false; double amountToPay = amount * level.getDiscount(); if (balance >= amountToPay) { balance -= amountToPay; accumulatedExpense += amountToPay; transactionHistory.add(new TransactionRecord( LocalDate.now(), -amountToPay, TransactionType.PAYMENT, category)); checkMembershipUpgrade(); return true; } return false; } // 验证授权码(手机/身份证/卡号后6位) private boolean verifyAuthCode(String authCode) { if (authCode == null || authCode.length() != 6) return false; return (phone != null && phone.length() > 6 && phone.substring(phone.length() - 6).equals(authCode)) || (idNumber != null && idNumber.length() > 6 && idNumber.substring(idNumber.length() - 6).equals(authCode)) || (cardNumber != null && cardNumber.length() > 6 && cardNumber.substring(cardNumber.length() - 6).equals(authCode)); } // Getters public String getCardNumber() { return cardNumber; } public String getName() { return name; } public String getGender() { return gender; } public int getAge() { return age; } public String getOccupation() { return occupation; } public String getPhone() { return phone; } public String getIdNumber() { return idNumber; } public MembershipLevel getLevel() { return level; } public double getBalance() { return balance; } public LocalDate getRegistrationDate() { return registrationDate; } public double getAccumulatedExpense() { return accumulatedExpense; } public List<TransactionRecord> getTransactionHistory() { return transactionHistory; } } // 会员管理系统类 class MembershipSystem { private Map<String, Member> members; private static final String ADMIN_USER = "admin"; private static final String ADMIN_PASS = "admin123"; public MembershipSystem() { members = new HashMap<>(); // 添加测试数据 addTestData(); } private void addTestData() { Member m1 = new Member("CN10001", "张三", "男", 30, "工程师", "13800138000", "110101199001011234"); m1.recharge(1000, "800000"); m1.deduct(200, "234", ConsumptionType.SHOPPING); members.put(m1.getCardNumber(), m1); Member m2 = new Member("CN10002", "李四", "女", 28, "设计师", "13900139000", "110101199002022345"); m2.recharge(2000, "90000"); m2.deduct(500, "345", ConsumptionType.FRESH_FOOD); members.put(m2.getCardNumber(), m2); // 模拟会员升级(修改注册日期) Member m3 = new Member("CN10003", "王五", "男", 35, "经理", "13600136000", "110101198511113333"); m3.recharge(5000, "36000"); // 设置注册日期为6个月前 m3 = modifyRegistrationDate(m3, LocalDate.now().minusMonths(6)); // 设置累计消费达到升级条件 m3 = modifyAccumulatedExpense(m3, 6000); members.put(m3.getCardNumber(), m3); } // 辅助方法(仅用于测试) private Member modifyRegistrationDate(Member member, LocalDate newDate) { try { java.lang.reflect.Field field = Member.class.getDeclaredField("registrationDate"); field.setAccessible(true); field.set(member, newDate); return member; } catch (Exception e) { e.printStackTrace(); return member; } } private Member modifyAccumulatedExpense(Member member, double amount) { try { java.lang.reflect.Field field = Member.class.getDeclaredField("accumulatedExpense"); field.setAccessible(true); field.set(member, amount); return member; } catch (Exception e) { e.printStackTrace(); return member; } } // 管理员验证 public boolean authenticateAdmin(String username, String password) { return ADMIN_USER.equals(username) && ADMIN_PASS.equals(password); } // 添加新会员 public void addMember(Member member) { members.put(member.getCardNumber(), member); } // 查找会员 public Member getMember(String cardNumber) { return members.get(cardNumber); } // 获取所有会员 public List<Member> getAllMembers() { return new ArrayList<>(members.values()); } // 获取会员卡号是否已存在 public boolean isCardNumberExists(String cardNumber) { return members.containsKey(cardNumber); } } // GUI主类 public class MembershipManagementApp extends JFrame { private MembershipSystem system; private JPanel cardPanel; private CardLayout cardLayout; private DefaultListModel<Member> listModel; private JList<Member> memberList; private Member selectedMember; private JTextArea detailsArea; private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); public MembershipManagementApp() { system = new MembershipSystem(); initializeUI(); } private void initializeUI() { setTitle("综合智慧会员管理系统"); setSize(900, 650); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); // 使用卡片布局 cardLayout = new CardLayout(); cardPanel = new JPanel(cardLayout); // 创建登录面板 JPanel loginPanel = createLoginPanel(); cardPanel.add(loginPanel, "login"); // 创建主功能面板 JPanel mainPanel = createMainPanel(); cardPanel.add(mainPanel, "main"); add(cardPanel); cardLayout.show(cardPanel, "login"); } private JPanel createLoginPanel() { JPanel panel = new JPanel(new GridBagLayout()); panel.setBackground(new Color(245, 245, 245)); panel.setBorder(new EmptyBorder(20, 20, 20, 20)); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(15, 15, 15, 15); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; JLabel titleLabel = new JLabel("综合智慧会员管理系统"); titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28)); titleLabel.setForeground(new Color(70, 130, 180)); panel.add(titleLabel, gbc); gbc.gridwidth = 1; gbc.gridy++; // 用户名和密码区域 JPanel inputPanel = new JPanel(new GridLayout(2, 2, 10, 15)); inputPanel.setBorder(BorderFactory.createTitledBorder("管理员登录")); inputPanel.setBackground(new Color(240, 248, 255)); inputPanel.setPreferredSize(new Dimension(350, 150)); JLabel userLabel = new JLabel("用户名:"); userLabel.setFont(new Font("宋体", Font.PLAIN, 16)); JTextField userField = new JTextField(15); userField.setFont(new Font("宋体", Font.PLAIN, 16)); JLabel passLabel = new JLabel("密码:"); passLabel.setFont(new Font("宋体", Font.PLAIN, 16)); JPasswordField passField = new JPasswordField(15); passField.setFont(new Font("宋体", Font.PLAIN, 16)); inputPanel.add(userLabel); inputPanel.add(userField); inputPanel.add(passLabel); inputPanel.add(passField); gbc.gridx = 0; gbc.gridy++; panel.add(inputPanel, gbc); gbc.gridy++; JButton loginBtn = new JButton("登录"); loginBtn.setFont(new Font("微软雅黑", Font.BOLD, 16)); loginBtn.setBackground(new Color(70, 130, 180)); loginBtn.setForeground(Color.WHITE); loginBtn.setPreferredSize(new Dimension(120, 40)); loginBtn.addActionListener(e -> { String username = userField.getText(); String password = new String(passField.getPassword()); if (system.authenticateAdmin(username, password)) { cardLayout.show(cardPanel, "main"); loadMemberList(); } else { JOptionPane.showMessageDialog(this, "用户名或密码错误!", "登录失败", JOptionPane.ERROR_MESSAGE); } }); panel.add(loginBtn, gbc); // 回车键登录功能 passField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { loginBtn.doClick(); } } }); return panel; } private JPanel createMainPanel() { JPanel panel = new JPanel(new BorderLayout(10, 10)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); // 顶部菜单栏 JMenuBar menuBar = new JMenuBar(); JMenu memberMenu = new JMenu("会员管理"); memberMenu.setFont(new Font("微软雅黑", Font.PLAIN, 14)); JMenuItem addMemberItem = new JMenuItem("添加新会员"); addMemberItem.addActionListener(e -> showAddMemberDialog()); addMemberItem.setFont(new Font("微软雅黑", Font.PLAIN, 14)); JMenuItem searchMemberItem = new JMenuItem("查找会员"); searchMemberItem.setFont(new Font("微软雅黑", Font.PLAIN, 14)); searchMemberItem.addActionListener(e -> showSearchDialog()); memberMenu.add(addMemberItem); memberMenu.add(searchMemberItem); menuBar.add(memberMenu); JMenu reportMenu = new JMenu("报表"); reportMenu.setFont(new Font("微软雅黑", Font.PLAIN, 14)); JMenuItem salesReportItem = new JMenuItem("销售分析"); salesReportItem.setFont(new Font("微软雅黑", Font.PLAIN, 14)); salesReportItem.addActionListener(e -> showSalesReport()); JMenuItem memberReportItem = new JMenuItem("会员统计"); memberReportItem.setFont(new Font("微软雅黑", Font.PLAIN, 14)); memberReportItem.addActionListener(e -> showMemberStatistics()); reportMenu.add(salesReportItem); reportMenu.add(memberReportItem); menuBar.add(reportMenu); panel.add(menuBar, BorderLayout.NORTH); // 主内容区域 JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setDividerLocation(250); // 左侧会员列表 listModel = new DefaultListModel<>(); memberList = new JList<>(listModel); memberList.setCellRenderer(new MemberListRenderer()); memberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); memberList.setFont(new Font("微软雅黑", Font.PLAIN, 14)); memberList.addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) { selectedMember = memberList.getSelectedValue(); showMemberDetails(selectedMember); } }); JScrollPane listScroll = new JScrollPane(memberList); listScroll.setBorder(BorderFactory.createTitledBorder("会员列表")); splitPane.setLeftComponent(listScroll); // 中间会员详情 JPanel detailPanel = new JPanel(new BorderLayout()); detailPanel.setBorder(BorderFactory.createTitledBorder("会员详情")); detailsArea = new JTextArea(); detailsArea.setEditable(false); detailsArea.setFont(new Font("微软雅黑", Font.PLAIN, 14)); detailsArea.setBorder(new EmptyBorder(10, 10, 10, 10)); detailPanel.add(new JScrollPane(detailsArea), BorderLayout.CENTER); // 底部操作按钮 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15)); JButton rechargeBtn = new JButton("充值"); rechargeBtn.setFont(new Font("微软雅黑", Font.BOLD, 14)); rechargeBtn.setPreferredSize(new Dimension(120, 35)); rechargeBtn.addActionListener(e -> showRechargeDialog()); JButton payBtn = new JButton("消费"); payBtn.setFont(new Font("微软雅黑", Font.BOLD, 14)); payBtn.setPreferredSize(new Dimension(120, 35)); payBtn.addActionListener(e -> showPaymentDialog()); JButton historyBtn = new JButton("查看记录"); historyBtn.setFont(new Font("微软雅黑", Font.BOLD, 14)); historyBtn.setPreferredSize(new Dimension(120, 35)); historyBtn.addActionListener(e -> showTransactionHistory()); JButton upgradeBtn = new JButton("强制升级"); upgradeBtn.setFont(new Font("微软雅黑", Font.BOLD, 14)); upgradeBtn.setPreferredSize(new Dimension(120, 35)); upgradeBtn.addActionListener(e -> forceUpgrade()); buttonPanel.add(rechargeBtn); buttonPanel.add(payBtn); buttonPanel.add(historyBtn); buttonPanel.add(upgradeBtn); detailPanel.add(buttonPanel, BorderLayout.SOUTH); splitPane.setRightComponent(detailPanel); panel.add(splitPane, BorderLayout.CENTER); // 状态栏 JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JLabel statusLabel = new JLabel("就绪"); statusLabel.setFont(new Font("微软雅黑", Font.PLAIN,12)); statusPanel.add(statusLabel); panel.add(statusPanel, BorderLayout.SOUTH); return panel; } private void loadMemberList() { listModel.clear(); for (Member member : system.getAllMembers()) { listModel.addElement(member); } } private void showMemberDetails(Member member) { if (member == null) { detailsArea.setText("请从左侧列表选择会员"); return; } StringBuilder sb = new StringBuilder(); sb.append("卡号: ").append(member.getCardNumber()).append("\n"); sb.append("姓名: ").append(member.getName()).append("\n"); sb.append("性别: ").append(member.getGender()).append("\n"); sb.append("年龄: ").append(member.getAge()).append("\n"); sb.append("职业: ").append(member.getOccupation()).append("\n"); sb.append("手机: ").append(member.getPhone()).append("\n"); sb.append("身份证: ").append(member.getIdNumber()).append("\n\n"); sb.append("等级: ").append(member.getLevel().getName()).append("\n"); sb.append("余额: ¥").append(String.format("%.2f", member.getBalance())).append("\n"); sb.append("累计消费: ¥").append(String.format("%.2f", member.getAccumulatedExpense())).append("\n"); sb.append("注册日期: ").append(member.getRegistrationDate().format(dateFormatter)).append("\n"); sb.append("会员天数: ").append(ChronoUnit.DAYS.between(member.getRegistrationDate(), LocalDate.now())).append("\n"); detailsArea.setText(sb.toString()); } private void showAddMemberDialog() { JDialog dialog = new JDialog(this, "添加新会员", true); dialog.setSize(500,450); JPanel panel = new JPanel(new GridLayout(9, 2, 10, 10)); panel.setBorder(new EmptyBorder(15,15,15,15)); // 表单字段 JTextField cardField = new JTextField(); JTextField nameField = new JTextField(); JTextField genderField = new JTextField(); JTextField ageField = new JTextField(); JTextField occupationField = new JTextField(); JTextField phoneField = new JTextField(); JTextField idField = new JTextField(); panel.add(new JLabel("卡号*:")); panel.add(cardField); panel.add(new JLabel("姓名*:")); panel.add(nameField); panel.add(new JLabel("性别:")); panel.add(genderField); panel.add(new JLabel("年龄:")); panel.add(ageField); panel.add(new JLabel("职业:")); panel.add(occupationField); panel.add(new JLabel("手机*:")); panel.add(phoneField); panel.add(new JLabel("身份证*:")); panel.add(idField); panel.add(new JLabel("")); // 占位符 JButton addBtn = new JButton("添加"); panel.add(addBtn); addBtn.addActionListener(e -> { // 验证必填字段 if (cardField.getText().isEmpty() || nameField.getText().isEmpty() || phoneField.getText().isEmpty() || idField.getText().isEmpty()) { JOptionPane.showMessageDialog(dialog, "带*的字段不能为空", "输入错误", JOptionPane.ERROR_MESSAGE); return; } if (system.isCardNumberExists(cardField.getText())) { JOptionPane.showMessageDialog(dialog, "该卡号已存在", "输入错误", JOptionPane.ERROR_MESSAGE); return; } try { int age = ageField.getText().isEmpty() ? 0 : Integer.parseInt(ageField.getText()); Member member = new Member( cardField.getText(), nameField.getText(), genderField.getText(), age, occupationField.getText(), phoneField.getText(), idField.getText() ); system.addMember(member); loadMemberList(); dialog.dispose(); JOptionPane.showMessageDialog(this, "会员添加成功"); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(dialog, "年龄必须是整数", "输入错误", JOptionPane.ERROR_MESSAGE); } }); dialog.add(panel); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void showRechargeDialog() { if (selectedMember == null) { JOptionPane.showMessageDialog(this, "请先选择一个会员", "操作失败", JOptionPane.WARNING_MESSAGE); return; } JDialog dialog = new JDialog(this, "会员充值", true); dialog.setSize(400,200); JPanel panel = new JPanel(new GridLayout(3,2,10,10)); panel.setBorder(new EmptyBorder(15,15,15,15)); panel.add(new JLabel("当前余额:")); panel.add(new JLabel(String.format("¥%.2f", selectedMember.getBalance()))); panel.add(new JLabel("充值金额*:")); JTextField amountField = new JTextField(); panel.add(amountField); panel.add(new JLabel("授权码(后6位):")); JTextField authField = new JTextField(); panel.add(authField); JButton rechargeBtn = new JButton("确认充值"); panel.add(new JLabel("")); panel.add(rechargeBtn); rechargeBtn.addActionListener(e -> { try { double amount = Double.parseDouble(amountField.getText()); if (amount <= 0) throw new NumberFormatException(); if (selectedMember.recharge(amount, authField.getText())) { JOptionPane.showMessageDialog(dialog, "充值成功"); showMemberDetails(selectedMember); dialog.dispose(); } else { JOptionPane.showMessageDialog(dialog, "授权码验证失败", "充值失败", JOptionPane.ERROR_MESSAGE); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(dialog, "请输入有效的充值金额", "输入错误", JOptionPane.ERROR_MESSAGE); } }); dialog.add(panel); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void showPaymentDialog() { if (selectedMember == null) { JOptionPane.showMessageDialog(this, "请先选择一个会员", "操作失败", JOptionPane.WARNING_MESSAGE); return; } JDialog dialog = new JDialog(this, "会员消费", true); dialog.setSize(400,250); JPanel panel = new JPanel(new GridLayout(4,2,10,10)); panel.setBorder(new EmptyBorder(15,15,15,15)); panel.add(new JLabel("当前余额:")); panel.add(new JLabel(String.format("¥%.2f", selectedMember.getBalance()))); panel.add(new JLabel("消费金额*:")); JTextField amountField = new JTextField(); panel.add(amountField); panel.add(new JLabel("消费类型:")); JComboBox<ConsumptionType> typeCombo = new JComboBox<>(ConsumptionType.values()); panel.add(typeCombo); panel.add(new JLabel("授权码(后6位):")); JTextField authField = new JTextField(); panel.add(authField); JButton payBtn = new JButton("确认支付"); panel.add(new JLabel("")); panel.add(payBtn); payBtn.addActionListener(e -> { try { double amount = Double.parseDouble(amountField.getText()); if (amount <= 0) throw new NumberFormatException(); ConsumptionType type = (ConsumptionType) typeCombo.getSelectedItem(); if (selectedMember.deduct(amount, authField.getText(), type)) { double actualPay = amount * selectedMember.getLevel().getDiscount(); JOptionPane.showMessageDialog(dialog, String.format("支付成功! 实际支付: ¥%.2f (折扣率:%.0f%%)", actualPay, (1 - selectedMember.getLevel().getDiscount()) * 100)); showMemberDetails(selectedMember); dialog.dispose(); } else { JOptionPane.showMessageDialog(dialog, "授权码验证失败或余额不足", "支付失败", JOptionPane.ERROR_MESSAGE); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(dialog, "请输入有效的消费金额", "输入错误", JOptionPane.ERROR_MESSAGE); } }); dialog.add(panel); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void showTransactionHistory() { if (selectedMember == null) { JOptionPane.showMessageDialog(this, "请先选择一个会员", "操作失败", JOptionPane.WARNING_MESSAGE); return; } List<TransactionRecord> transactions = selectedMember.getTransactionHistory(); if (transactions.isEmpty()) { JOptionPane.showMessageDialog(this, "该会员暂无交易记录", "交易历史", JOptionPane.INFORMATION_MESSAGE); return; } JDialog dialog = new JDialog(this, "交易记录 - " + selectedMember.getName(), true); dialog.setSize(600,400); // 创建表格 String[] columns = {"日期", "类型", "金额", "消费类型"}; DefaultTableModel model = new DefaultTableModel(columns, 0); for (TransactionRecord tr : transactions) { Object[] row = { tr.getDate().format(dateFormatter), tr.getType().getDisplayName(), String.format("%.2f", tr.getAmount()), tr.getCategory() == null ? "" : tr.getCategory().getName() }; model.addRow(row); } JTable table = new JTable(model); JScrollPane scrollPane = new JScrollPane(table); dialog.add(scrollPane); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void forceUpgrade() { if (selectedMember == null) { JOptionPane.showMessageDialog(this, "请先选择一个会员", "操作失败", JOptionPane.WARNING_MESSAGE); return; } MembershipLevel[] levels = MembershipLevel.values(); int currentIndex = Arrays.asList(levels).indexOf(selectedMember.getLevel()); if (currentIndex == 0) { JOptionPane.showMessageDialog(this, "该会员已经是最高等级", "强制升级", JOptionPane.INFORMATION_MESSAGE); return; } MembershipLevel nextLevel = levels[currentIndex - 1]; // 反向获取更高等级 String[] options = {"确认", "取消"}; int choice = JOptionPane.showOptionDialog( this, "将会员 " + selectedMember.getName() + " 从 " + selectedMember.getLevel().getName() + " 升级到 " + nextLevel.getName() + "?", "强制升级确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); if (choice == 0) { // 确认 // 通过反射强制修改会员等级 try { java.lang.reflect.Field levelField = Member.class.getDeclaredField("level"); levelField.setAccessible(true); levelField.set(selectedMember, nextLevel); showMemberDetails(selectedMember); JOptionPane.showMessageDialog(this, "升级成功!"); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "升级失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } private void showSearchDialog() { JDialog dialog = new JDialog(this, "查找会员", true); dialog.setSize(400,150); JPanel panel = new JPanel(new GridLayout(3,2,10,10)); panel.setBorder(new EmptyBorder(15,15,15,15)); panel.add(new JLabel("搜索条件:")); JComboBox<String> criteriaCombo = new JComboBox<>(new String[]{"卡号", "姓名", "手机"}); panel.add(criteriaCombo); panel.add(new JLabel("搜索内容:")); JTextField searchField = new JTextField(); panel.add(searchField); JButton searchBtn = new JButton("搜索"); panel.add(new JLabel("")); panel.add(searchBtn); searchBtn.addActionListener(e -> { String criteria = (String) criteriaCombo.getSelectedItem(); String value = searchField.getText().trim(); Member found = null; for (Member m : system.getAllMembers()) { if ("卡号".equals(criteria) && m.getCardNumber().equals(value)) { found = m; break; } else if ("姓名".equals(criteria) && m.getName().contains(value)) { found = m; break; } else if ("手机".equals(criteria) && m.getPhone().contains(value)) { found = m; break; } } if (found != null) { memberList.setSelectedValue(found, true); showMemberDetails(found); dialog.dispose(); } else { JOptionPane.showMessageDialog(dialog, "未找到匹配的会员", "搜索结果", JOptionPane.INFORMATION_MESSAGE); } }); dialog.add(panel); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void showSalesReport() { JDialog dialog = new JDialog(this, "销售分析报告", true); dialog.setSize(600,500); JTextArea reportArea = new JTextArea(); reportArea.setFont(new Font("微软雅黑", Font.PLAIN,14)); // 计算统计数据 double totalRecharge = 0; double totalExpenses = 0; Map<ConsumptionType, Double> expensesByCategory = new EnumMap<>(ConsumptionType.class); Map<MembershipLevel, Double> expensesByLevel = new EnumMap<>(MembershipLevel.class); for (Member m : system.getAllMembers()) { for (TransactionRecord tr : m.getTransactionHistory()) { if (tr.getType() == TransactionType.RECHARGE) { totalRecharge += tr.getAmount(); } else if (tr.getType() == TransactionType.PAYMENT) { double amount = Math.abs(tr.getAmount()); totalExpenses += amount; // 按消费类型统计 ConsumptionType category = tr.getCategory(); expensesByCategory.put(category, expensesByCategory.getOrDefault(category, 0.0) + amount); // 按会员等级统计 expensesByLevel.put(m.getLevel(), expensesByLevel.getOrDefault(m.getLevel(), 0.0) + amount); } } } // 生成报告 StringBuilder report = new StringBuilder(); report.append("===== 销售分析报告 =====\n\n"); report.append(String.format("总收入: ¥%.2f\n", totalRecharge)); report.append(String.format("总消费: ¥%.2f\n\n", totalExpenses)); report.append("---- 按消费类型分布 ----\n"); for (ConsumptionType type : ConsumptionType.values()) { double amount = expensesByCategory.getOrDefault(type, 0.0); if (amount > 0) { report.append(String.format("%-12s: ¥%.2f (%.1f%%)\n", type.getName(), amount, (amount / totalExpenses) * 100)); } } report.append("\n---- 按会员等级分布 ----\n"); for (MembershipLevel level : MembershipLevel.values()) { double amount = expensesByLevel.getOrDefault(level, 0.0); if (amount > 0) { report.append(String.format("%-8s: ¥%.2f (%.1f%%)\n", level.getName(), amount, (amount / totalExpenses) * 100)); } } reportArea.setText(report.toString()); dialog.add(new JScrollPane(reportArea)); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } private void showMemberStatistics() { JDialog dialog = new JDialog(this, "会员统计报告", true); dialog.setSize(500,400); // 计算统计数据 Map<MembershipLevel, Integer> countByLevel = new EnumMap<>(MembershipLevel.class); int totalMembers = system.getAllMembers().size(); for (Member m : system.getAllMembers()) { countByLevel.put(m.getLevel(), countByLevel.getOrDefault(m.getLevel(), 0) + 1); } // 创建表格 String[] columns = {"会员等级", "会员数量", "占比"}; DefaultTableModel model = new DefaultTableModel(columns, 0); for (MembershipLevel level : MembershipLevel.values()) { int count = countByLevel.getOrDefault(level, 0); model.addRow(new Object[]{ level.getName(), count, String.format("%.1f%%", ((double)count / totalMembers) * 100) }); } model.addRow(new Object[]{ "总计", totalMembers, "100%" }); JTable table = new JTable(model); JScrollPane scrollPane = new JScrollPane(table); dialog.add(scrollPane); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { MembershipManagementApp app = new MembershipManagementApp(); app.setVisible(true); }); } } //自定义会员列表渲染器 class MemberListRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof Member) { Member member = (Member) value; setText(member.getCardNumber() + " - " + member.getName() + " (" + member.getLevel().getName() + ")"); // 根据会员等级设置不同颜色 switch (member.getLevel()) { case DIAMOND: setBackground(isSelected ? new Color(180, 230, 255) : new Color(200, 240, 255)); setForeground(Color.BLUE); break; case PLATINUM: setBackground(isSelected ? new Color(220, 240, 255) : new Color(230, 245, 255)); setForeground(new Color(0, 100, 0)); break; case GOLD: setBackground(isSelected ? new Color(255, 250, 200) : new Color(255, 255, 220)); setForeground(new Color(140, 70, 0)); break; default: // SILVER setBackground(isSelected ? new Color(220, 220, 220) : Color.WHITE); break; } } return this; } } 依据上面代码,增加删除与修改会员功能
06-11
import java.awt.*; import javax.swing.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import javax.swing.table.DefaultTableModel; public class LoginWindow { private JFrame frame; private JTextField txtUser; private JPasswordField txtPassword; private JRadioButton r1, r2; private ButtonGroup bg; private JComboBox<String> city; private JButton btnLogin, btnReset; private JCheckBox c1, c2, c3; private MainPage mainPage; public static void main(String[] args) { SwingUtilities.invokeLater(() -> new LoginWindow().show()); } public LoginWindow() { frame = new JFrame("电商购物平台 - 登录"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); frame.setLocationRelativeTo(null); frame.getContentPane().setLayout(null); // 用户名标签和文本框 JLabel lblUser = new JLabel("账号:"); lblUser.setBounds(64, 46, 69, 15); frame.getContentPane().add(lblUser); txtUser = new JTextField(); txtUser.setBounds(167, 43, 193, 21); frame.getContentPane().add(txtUser); // 密码标签和密码框 JLabel lblPassword = new JLabel("密码:"); lblPassword.setBounds(64, 86, 69, 15); frame.getContentPane().add(lblPassword); txtPassword = new JPasswordField(); txtPassword.setBounds(167, 83, 193, 21); frame.getContentPane().add(txtPassword); // 性别单选按钮 r1 = new JRadioButton("男"); r1.setBounds(167, 123, 60, 21); r1.setSelected(true); frame.getContentPane().add(r1); r2 = new JRadioButton("女"); r2.setBounds(247, 123, 60, 21); frame.getContentPane().add(r2); bg = new ButtonGroup(); bg.add(r1); bg.add(r2); // 城市下拉框 city = new JComboBox<>(new String[]{"", "北京", "上海", "天津", "石家庄"}); city.setBounds(167, 163, 193, 21); frame.getContentPane().add(city); JLabel lblCity = new JLabel("所在城市:"); lblCity.setBounds(64, 166, 69, 15); frame.getContentPane().add(lblCity); // 兴趣爱好复选框 c1 = new JCheckBox("文学"); c1.setBounds(167, 203, 60, 21); frame.getContentPane().add(c1); c2 = new JCheckBox("体育"); c2.setBounds(247, 203, 60, 21); frame.getContentPane().add(c2); c3 = new JCheckBox("音乐"); c3.setBounds(327, 203, 60, 21); frame.getContentPane().add(c3); JLabel lblAihao = new JLabel("个人爱好:"); lblAihao.setBounds(64, 206, 69, 15); frame.getContentPane().add(lblAihao); // 登录按钮 btnLogin = new JButton("登 录"); btnLogin.setBounds(170, 250, 80, 30); btnLogin.setFont(new Font("微软雅黑", Font.BOLD, 14)); btnLogin.setForeground(Color.BLUE); btnLogin.setBorder(BorderFactory.createLineBorder(Color.BLUE)); btnLogin.addActionListener(e -> login()); frame.getContentPane().add(btnLogin); // 重置按钮 btnReset = new JButton("重 置"); btnReset.setBounds(260, 250, 80, 30); btnReset.setFont(new Font("微软雅黑", Font.BOLD, 14)); btnReset.setForeground(Color.BLUE); btnReset.setBorder(BorderFactory.createLineBorder(Color.BLUE)); btnReset.addActionListener(e -> reset()); frame.getContentPane().add(btnReset); } private void login() { String name = txtUser.getText(); String password = new String(txtPassword.getPassword()); if (!name.isEmpty() && !password.isEmpty()) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 加载 JDBC 驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 获取数据库连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "SELECT * FROM yonghu WHERE yhMC = ? AND yhXB = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, password); rs = pstmt.executeQuery(); if (rs.next()) { // 创建并显示主页面 if (mainPage == null) { mainPage = new MainPage(); } mainPage.setVisible(true); frame.setVisible(false); } else { JOptionPane.showMessageDialog(frame, "用户名或密码错误!", "错误", JOptionPane.ERROR_MESSAGE); } } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(frame, "未找到 MySQL JDBC 驱动!", "错误", JOptionPane.ERROR_MESSAGE); } catch (SQLException e) { JOptionPane.showMessageDialog(frame, "数据库连接失败!", "错误", JOptionPane.ERROR_MESSAGE); } finally { // 关闭资源 try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } else { JOptionPane.showMessageDialog(frame, "用户名和密码不能为空!", "错误", JOptionPane.ERROR_MESSAGE); } } private void reset() { txtUser.setText(""); txtPassword.setText(""); r1.setSelected(true); r2.setSelected(false); city.setSelectedIndex(0); c1.setSelected(false); c2.setSelected(false); c3.setSelected(false); } public void show() { frame.setVisible(true); } // 主页面类 public class MainPage extends JFrame { public MainPage() { setTitle("电商购物平台 - 主页面"); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 添加主页面的内容 JLabel welcomeLabel = new JLabel("欢迎使用电商购物平台。"); welcomeLabel.setHorizontalAlignment(JLabel.CENTER); welcomeLabel.setFont(new Font("微软雅黑", Font.BOLD, 18)); add(welcomeLabel); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 创建菜单 JMenu productMenu = new JMenu("商品管理"); JMenu userMenu = new JMenu("用户管理"); JMenu orderMenu = new JMenu("订单管理"); JMenu purchaseMenu = new JMenu("购买"); // 创建菜单项 JMenuItem addProduct = new JMenuItem("商品新增"); JMenuItem modifyProduct = new JMenuItem("商品修改"); JMenuItem deleteProduct = new JMenuItem("商品删除"); JMenuItem queryProduct = new JMenuItem("商品查询"); JMenuItem addUser = new JMenuItem("用户新增"); JMenuItem modifyUser = new JMenuItem("用户修改"); JMenuItem deleteUser = new JMenuItem("用户删除"); JMenuItem queryUser = new JMenuItem("用户查询"); JMenuItem queryOrder = new JMenuItem("订单查询"); JMenuItem deleteOrder = new JMenuItem("订单删除"); JMenuItem modifyOrder = new JMenuItem("订单修改"); JMenuItem buyProduct = new JMenuItem("商品购买"); // 将菜单项添加到菜单 productMenu.add(addProduct); productMenu.add(modifyProduct); productMenu.add(deleteProduct); productMenu.add(queryProduct); userMenu.add(addUser); userMenu.add(modifyUser); userMenu.add(deleteUser); userMenu.add(queryUser); orderMenu.add(queryOrder); orderMenu.add(deleteOrder); orderMenu.add(modifyOrder); purchaseMenu.add(buyProduct); // 将菜单添加到菜单栏 menuBar.add(productMenu); menuBar.add(userMenu); menuBar.add(orderMenu); menuBar.add(purchaseMenu); // 设置菜单栏 setJMenuBar(menuBar); // 添加菜单项的事件监听器 addProduct.addActionListener(e -> { new AddProductFrame().setVisible(true); }); modifyProduct.addActionListener(e -> { new ModifyProductFrame().setVisible(true); }); queryProduct.addActionListener(e -> { new QueryProductFrame().setVisible(true); }); // 其他菜单项的监听器可以类似地添加 } } // 商品新增窗口 public class AddProductFrame extends JFrame { public AddProductFrame() { setTitle("商品新增"); setSize(400, 600); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // 商品ID JLabel productIdLabel = new JLabel("商品ID:"); JTextField productIdText = new JTextField(); productIdText.setPreferredSize(new Dimension(200, 25)); JPanel productIdPanel = new JPanel(); productIdPanel.add(productIdLabel); productIdPanel.add(productIdText); // 商品名称 JLabel productNameLabel = new JLabel("商品名称:"); JTextField productNameText = new JTextField(); productNameText.setPreferredSize(new Dimension(200, 25)); JPanel productNamePanel = new JPanel(); productNamePanel.add(productNameLabel); productNamePanel.add(productNameText); // 商品价格 JLabel productPriceLabel = new JLabel("商品价格:"); JTextField productPriceText = new JTextField(); productPriceText.setPreferredSize(new Dimension(200, 25)); JPanel productPricePanel = new JPanel(); productPricePanel.add(productPriceLabel); productPricePanel.add(productPriceText); // 商品类别 JLabel productCategoryLabel = new JLabel("商品类别:"); JComboBox<String> productCategoryComboBox = new JComboBox<>(new String[]{"", "电子产品", "服装", "食品", "书籍"}); productCategoryComboBox.setPreferredSize(new Dimension(200, 25)); JPanel productCategoryPanel = new JPanel(); productCategoryPanel.add(productCategoryLabel); productCategoryPanel.add(productCategoryComboBox); // 商品产地 JLabel productOriginLabel = new JLabel("商品产地:"); JTextField productOriginText = new JTextField(); productOriginText.setPreferredSize(new Dimension(200, 25)); JPanel productOriginPanel = new JPanel(); productOriginPanel.add(productOriginLabel); productOriginPanel.add(productOriginText); // 商品简介 JLabel productDescriptionLabel = new JLabel("商品简介:"); JTextArea productDescriptionArea = new JTextArea(5, 25); JScrollPane descriptionScrollPane = new JScrollPane(productDescriptionArea); descriptionScrollPane.setPreferredSize(new Dimension(200, 100)); JPanel productDescriptionPanel = new JPanel(); productDescriptionPanel.add(productDescriptionLabel); productDescriptionPanel.add(descriptionScrollPane); // 按钮面板 JButton saveButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JPanel buttonPanel = new JPanel(); buttonPanel.add(saveButton); buttonPanel.add(cancelButton); // 添加所有面板到主面板 panel.add(productIdPanel); panel.add(productNamePanel); panel.add(productPricePanel); panel.add(productCategoryPanel); panel.add(productOriginPanel); panel.add(productDescriptionPanel); panel.add(buttonPanel); // 将主面板添加到窗口 add(panel); // 添加按钮事件监听 saveButton.addActionListener(e -> { Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "INSERT INTO shangpin (spMC, spLB, spJG, spCD, spJJ) VALUES (?, ?, ?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, productNameText.getText()); pstmt.setString(2, productCategoryComboBox.getSelectedItem().toString()); pstmt.setFloat(3, Float.parseFloat(productPriceText.getText())); pstmt.setString(4, productOriginText.getText()); pstmt.setString(5, productDescriptionArea.getText()); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { JOptionPane.showMessageDialog(this, "商品新增成功!"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "商品新增失败!"); ex.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }); cancelButton.addActionListener(e -> { dispose(); }); } } // 商品修改窗口 public class ModifyProductFrame extends JFrame { public ModifyProductFrame() { setTitle("商品修改"); setSize(400, 600); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // 商品ID查询 JLabel searchIdLabel = new JLabel("请输入商品ID:"); JTextField searchIdText = new JTextField(); searchIdText.setPreferredSize(new Dimension(200, 25)); JButton searchButton = new JButton("查询"); JPanel searchPanel = new JPanel(); searchPanel.add(searchIdLabel); searchPanel.add(searchIdText); searchPanel.add(searchButton); // 商品ID显示 JLabel productIdLabel = new JLabel("商品ID:"); JTextField productIdText = new JTextField(); productIdText.setEditable(false); productIdText.setPreferredSize(new Dimension(200, 25)); JPanel productIdPanel = new JPanel(); productIdPanel.add(productIdLabel); productIdPanel.add(productIdText); // 商品名称 JLabel productNameLabel = new JLabel("商品名称:"); JTextField productNameText = new JTextField(); productNameText.setPreferredSize(new Dimension(200, 25)); JPanel productNamePanel = new JPanel(); productNamePanel.add(productNameLabel); productNamePanel.add(productNameText); // 商品价格 JLabel productPriceLabel = new JLabel("商品价格:"); JTextField productPriceText = new JTextField(); productPriceText.setPreferredSize(new Dimension(200, 25)); JPanel productPricePanel = new JPanel(); productPricePanel.add(productPriceLabel); productPricePanel.add(productPriceText); // 商品类别 JLabel productCategoryLabel = new JLabel("商品类别:"); JComboBox<String> productCategoryComboBox = new JComboBox<>(new String[]{"", "电子产品", "服装", "食品", "书籍"}); productCategoryComboBox.setPreferredSize(new Dimension(200, 25)); JPanel productCategoryPanel = new JPanel(); productCategoryPanel.add(productCategoryLabel); productCategoryPanel.add(productCategoryComboBox); // 商品产地 JLabel productOriginLabel = new JLabel("商品产地:"); JTextField productOriginText = new JTextField(); productOriginText.setPreferredSize(new Dimension(200, 25)); JPanel productOriginPanel = new JPanel(); productOriginPanel.add(productOriginLabel); productOriginPanel.add(productOriginText); // 商品简介 JLabel productDescriptionLabel = new JLabel("商品简介:"); JTextArea productDescriptionArea = new JTextArea(5, 25); JScrollPane descriptionScrollPane = new JScrollPane(productDescriptionArea); descriptionScrollPane.setPreferredSize(new Dimension(200, 100)); JPanel productDescriptionPanel = new JPanel(); productDescriptionPanel.add(productDescriptionLabel); productDescriptionPanel.add(descriptionScrollPane); // 按钮面板 JButton updateButton = new JButton("修改"); JButton deleteButton = new JButton("删除"); JButton exitButton = new JButton("取消"); JPanel buttonPanel = new JPanel(); buttonPanel.add(updateButton); buttonPanel.add(deleteButton); buttonPanel.add(exitButton); // 添加所有面板到主面板 panel.add(searchPanel); panel.add(productIdPanel); panel.add(productNamePanel); panel.add(productPricePanel); panel.add(productCategoryPanel); panel.add(productOriginPanel); panel.add(productDescriptionPanel); panel.add(buttonPanel); // 将主面板添加到窗口 add(panel); // 添加按钮事件监听 searchButton.addActionListener(e -> { String productId = searchIdText.getText(); if (productId.isEmpty()) { JOptionPane.showMessageDialog(this, "请输入商品ID!"); return; } Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "SELECT * FROM shangpin WHERE spID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, productId); rs = pstmt.executeQuery(); if (rs.next()) { productIdText.setText(rs.getString("spID")); productNameText.setText(rs.getString("spMC")); productCategoryComboBox.setSelectedItem(rs.getString("spLB")); productPriceText.setText(rs.getString("spJG")); productOriginText.setText(rs.getString("spCD")); productDescriptionArea.setText(rs.getString("spJJ")); } else { JOptionPane.showMessageDialog(this, "未找到商品ID为 " + productId + " 的商品信息"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "查询失败!"); ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }); updateButton.addActionListener(e -> { Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "UPDATE shangpin SET spMC = ?, spLB = ?, spJG = ?, spCD = ?, spJJ = ? WHERE spID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, productNameText.getText()); pstmt.setString(2, productCategoryComboBox.getSelectedItem().toString()); pstmt.setFloat(3, Float.parseFloat(productPriceText.getText())); pstmt.setString(4, productOriginText.getText()); pstmt.setString(5, productDescriptionArea.getText()); pstmt.setString(6, productIdText.getText()); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { JOptionPane.showMessageDialog(this, "商品修改成功!"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "商品修改失败!"); ex.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }); deleteButton.addActionListener(e -> { Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "DELETE FROM shangpin WHERE spID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, productIdText.getText()); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { JOptionPane.showMessageDialog(this, "商品删除成功!"); dispose(); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "商品删除失败!"); ex.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }); exitButton.addActionListener(e -> { dispose(); }); } } // 商品查询窗口 public class QueryProductFrame extends JFrame { public QueryProductFrame() { setTitle("商品查询"); setSize(800, 600); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); // 北部面板 - 查询条件 JPanel northPanel = new JPanel(); northPanel.setLayout(new FlowLayout()); JLabel conditionLabel = new JLabel("查询条件:"); northPanel.add(conditionLabel); JButton queryAllButton = new JButton("查询所有商品信息"); northPanel.add(queryAllButton); JButton queryDepartmentButton = new JButton("查询部门员工信息"); northPanel.add(queryDepartmentButton); JLabel departmentLabel = new JLabel("部门:"); JComboBox<String> departmentComboBox = new JComboBox<>(new String[]{"", "设计部", "开发部", "市场部", "人事部"}); northPanel.add(departmentLabel); northPanel.add(departmentComboBox); // 中部面板 - 查询结果表格 JPanel centerPanel = new JPanel(); centerPanel.setLayout(new BorderLayout()); String[] columnNames = {"商品ID", "商品名称", "商品类别", "商品价格", "商品产地", "商品简介"}; Object[][] data = {}; JTable table = new JTable(data, columnNames); JScrollPane scrollPane = new JScrollPane(table); centerPanel.add(scrollPane, BorderLayout.CENTER); // 添加面板到窗口 add(northPanel, BorderLayout.NORTH); add(centerPanel, BorderLayout.CENTER); // 添加按钮事件监听 queryAllButton.addActionListener(e -> { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangpin", "your_username", "your_password"); String sql = "SELECT * FROM shangpin"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); // 获取查询结果并更新表格数据 ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); Object[][] newData = new Object[0][]; int rowCount = 0; while (rs.next()) { Object[] row = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = rs.getObject(i + 1); } newData = Arrays.copyOf(newData, newData.length + 1); newData[newData.length - 1] = row; rowCount++; } table.setModel(new DefaultTableModel(newData, columnNames)); } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "查询所有商品信息失败!"); ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }); queryDepartmentButton.addActionListener(e -> { String department = departmentComboBox.getSelectedItem().toString(); if (department.isEmpty()) { JOptionPane.showMessageDialog(this, "请选择部门!"); return; } JOptionPane.showMessageDialog(this, "查询 " + department + " 的商品信息成功!"); }); } } }为什么显示无法找到jdbc
06-08
package org.example; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.table.*; public class SimpleMySQLClient extends JFrame { private JTextField hostField, portField, userField, databaseField; private JPasswordField passwordField; private JTextArea sqlArea; private JTable resultTable; private DefaultTableModel tableModel; private Connection connection; public SimpleMySQLClient() { setTitle("简易 MySQL 客户端"); setSize(900, 700); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout(10, 10)); // 顶部连接信息面板 JPanel connectPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); gbc.fill = GridBagConstraints.HORIZONTAL; JLabel[] labels = { new JLabel("Host:"), new JLabel("Port:"), new JLabel("用户名:"), new JLabel("密码:"), new JLabel("数据库名:") }; JComponent[] fields = { hostField = new JTextField("localhost"), portField = new JTextField("3306"), userField = new JTextField("root"), passwordField = new JPasswordField(), databaseField = new JTextField() }; for (int i = 0; i < labels.length; i++) { gbc.gridx = 0; gbc.gridy = i; connectPanel.add(labels[i], gbc); gbc.gridx = 1; gbc.weightx = 1.0; connectPanel.add(fields[i], gbc); } JButton connectButton = new JButton("连接"); connectButton.addActionListener(this::connectToDatabase); gbc.gridx = 1; gbc.gridy = labels.length; gbc.anchor = GridBagConstraints.EAST; connectPanel.add(connectButton, gbc); add(new JScrollPane(connectPanel), BorderLayout.NORTH); // 中间 SQL 执行区域 JPanel sqlPanel = new JPanel(new BorderLayout()); sqlArea = new JTextArea(10, 40); sqlArea.setLineWrap(true); JScrollPane sqlScroll = new JScrollPane(sqlArea); JButton executeButton = new JButton("执行 SQL"); executeButton.addActionListener(this::executeSQL); sqlPanel.add(new JLabel("输入 SQL 语句:"), BorderLayout.NORTH); sqlPanel.add(sqlScroll, BorderLayout.CENTER); sqlPanel.add(executeButton, BorderLayout.SOUTH); add(sqlPanel, BorderLayout.CENTER); // 结果表格 tableModel = new DefaultTableModel(); resultTable = new JTable(tableModel); JScrollPane tableScroll = new JScrollPane(resultTable); add(tableScroll, BorderLayout.SOUTH); pack(); setLocationRelativeTo(null); // 居中窗口 setVisible(true); } // 以下方法与之前相同:connectToDatabase(), executeSQL(), main() // 省略代码,请使用你之前的功能代码 private void connectToDatabase(ActionEvent e) { String host = hostField.getText(); String port = portField.getText(); String user = userField.getText(); char[] passwordChars = passwordField.getPassword(); String password = new String(passwordChars); java.util.Arrays.fill(passwordChars, '\0'); String database = databaseField.getText(); String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?serverTimezone=UTC"; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection(url, user, password); JOptionPane.showMessageDialog(this, "连接成功!"); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "连接失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } private void executeSQL(ActionEvent e) { if (connection == null) { JOptionPane.showMessageDialog(this, "请先连接数据库", "提示", JOptionPane.WARNING_MESSAGE); return; } String sql = sqlArea.getText(); if (sql.trim().isEmpty()) { JOptionPane.showMessageDialog(this, "请输入 SQL 语句", "提示", JOptionPane.WARNING_MESSAGE); return; } try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); tableModel.setRowCount(0); tableModel.setColumnCount(0); for (int i = 1; i <= columnCount; i++) { tableModel.addColumn(metaData.getColumnLabel(i)); } while (rs.next()) { Object[] row = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = rs.getObject(i + 1); } tableModel.addRow(row); } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "执行 SQL 出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } public static void main(String[] args) { SwingUtilities.invokeLater(SimpleMySQLClient::new); } }
最新发布
08-20
package controller; import database.DatabaseConnection; import model.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class AuthController { private static User currentUser; public static boolean authenticate(String username, String password, String role) { String sql = "SELECT * FROM users WHERE username = ? AND password = ? AND role = ?"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, username); pstmt.setString(2, password); pstmt.setString(3, role); System.out.println("Executing query: SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "' AND role = '" + role + "'"); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { System.out.println("User authenticated: " + username); System.out.println("User authenticated: " + password); System.out.println("User ID: " + rs.getInt("id")); System.out.println("User Role: " + rs.getString("role")); currentUser = new User( rs.getInt("id"),username, password, role); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } public static User getCurrentUser() { return currentUser; } }package controller; import database.DatabaseConnection; import model.TrainingRecord; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class HistoryController { public static String getTrendAnalysis(String trainingName) { // 简单示例,可根据实际需求实现更复杂的趋势分析 return "暂无趋势分析数据。"; } public static List<TrainingRecord> getTrainingRecords(String trainingName) { List<TrainingRecord> records = new ArrayList<>(); String sql = "SELECT * FROM training_records WHERE training_name = ?"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, trainingName); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); int userId = rs.getInt("user_id"); int session = rs.getInt("session"); LocalDateTime startTime = rs.getObject("start_time", LocalDateTime.class); LocalDateTime endTime = rs.getObject("end_time", LocalDateTime.class); int score = rs.getInt("score"); String evaluation = rs.getString("evaluation"); TrainingRecord record = new TrainingRecord(id, userId, trainingName, session, startTime, endTime, score, evaluation); records.add(record); } } catch (SQLException e) { e.printStackTrace(); } return records; } }package controller; import database.TrainingDAO; import model.TrainingRecord; import java.time.LocalDateTime; public class TrainingController { public static int getNextSessionCount(String trainingName) { TrainingDAO trainingDAO = new TrainingDAO(); return trainingDAO.getNextSessionCount( AuthController.getCurrentUser().getId(), trainingName ); } public static void saveTrainingRecord(TrainingRecord record) { TrainingDAO trainingDAO = new TrainingDAO(); trainingDAO.saveTrainingRecord(record); } // AI接口预留方法 public static native int evaluateScore(String videoPath); public static native String generateEvaluation(String videoPath); public static native String analyzeTrends(int userId, String trainingName); }package database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DatabaseConnection { private static final String DB_URL = "jdbc:mysql://localhost:3306/db01"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "123456"; private static Connection connection; public static Connection getConnection() { if (connection == null) { try { return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); } catch (SQLException e) { e.printStackTrace(); } } return connection; } }package database; import model.TrainingRecord; import java.sql.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class TrainingDAO { public int getNextSessionCount(int userId, String trainingName) { String sql = "SELECT MAX(session) AS max_session FROM training_records " + "WHERE user_id = ? AND training_name = ?"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, userId); pstmt.setString(2, trainingName); try (ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { return rs.getInt("max_session") + 1; } } } catch (SQLException e) { e.printStackTrace(); } return 1; } public void saveTrainingRecord(TrainingRecord record) { String sql = "INSERT INTO training_records(user_id, training_name, session, " + "start_time, end_time, score, evaluation) " + "VALUES(?,?,?,?,?,?,?)"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, record.getUserId()); pstmt.setString(2, record.getTrainingName()); pstmt.setInt(3, record.getSession()); pstmt.setTimestamp(4, Timestamp.valueOf(record.getStartTime())); pstmt.setTimestamp(5, Timestamp.valueOf(record.getEndTime())); pstmt.setInt(6, record.getScore()); pstmt.setString(7, record.getEvaluation()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public List<TrainingRecord> getTrainingRecords(int userId, String trainingName) { List<TrainingRecord> records = new ArrayList<>(); String sql = "SELECT * FROM training_records " + "WHERE user_id = ? AND training_name = ? ORDER BY session"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, userId); pstmt.setString(2, trainingName); try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { TrainingRecord record = new TrainingRecord( rs.getInt("user_id"), rs.getString("training_name"), rs.getInt("session") ); record.setId(rs.getInt("id")); record.setStartTime(rs.getTimestamp("start_time").toLocalDateTime()); record.setEndTime(rs.getTimestamp("end_time").toLocalDateTime()); record.setScore(rs.getInt("score")); record.setEvaluation(rs.getString("evaluation")); records.add(record); } } } catch (SQLException e) { e.printStackTrace(); } return records; } }package database; import model.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserDAO { public User authenticate(String username, String password, String role) { String sql = "SELECT * FROM users WHERE username = ? AND password = ? AND role = ?"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { if (conn == null || conn.isClosed()) { System.err.println("Database connection is closed or null"); return null; } pstmt.setString(1, username); pstmt.setString(2, password); pstmt.setString(3, role.toLowerCase()); try (ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { User user = new User( rs.getInt("id"), rs.getString("username"), rs.getString("password"), rs.getString("role") ); user.setId(rs.getInt("id")); return user; } } } catch (SQLException e) { e.printStackTrace(); } return null; } }package model; import java.time.LocalDateTime; public class TrainingRecord { private int id; private int userId; private String trainingName; private int session; private LocalDateTime startTime; private LocalDateTime endTime; private int score; private String evaluation; public TrainingRecord(int userId, String trainingName, int session) { this.userId = userId; this.trainingName = trainingName; this.session = session; } public TrainingRecord(int id, int userId, String trainingName, int session, LocalDateTime startTime, LocalDateTime endTime, int score, String evaluation) { } // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getTrainingName() { return trainingName; } public void setTrainingName(String trainingName) { this.trainingName = trainingName; } public int getSession() { return session; } public void setSession(int session) { this.session = session; } public LocalDateTime getStartTime() { return startTime; } public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; } public LocalDateTime getEndTime() { return endTime; } public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getEvaluation() { return evaluation; } public void setEvaluation(String evaluation) { this.evaluation = evaluation; } }package model; public class User { private int id; private String username; private String password; private String role; public User(int id, String username, String password, String role) { this.id = id; this.username = username; this.password = password; this.role = role; } // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }package view; public class AppMain { public static void main(String[] args) { // 初始化数据库连接 database.DatabaseConnection.getConnection(); // 启动登录界面 javax.swing.SwingUtilities.invokeLater(() -> { LoginFrame loginFrame = new LoginFrame(); loginFrame.setVisible(true); }); } }package view; import controller.HistoryController; import model.TrainingRecord; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.category.DefaultCategoryDataset; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.util.List; public class HistoryDataFrame extends JFrame { public HistoryDataFrame(String trainingName) { setTitle(trainingName + " - 历史数据"); setSize(900, 600); setLocationRelativeTo(null); JTabbedPane tabbedPane = new JTabbedPane(); // 趋势分析标签页 tabbedPane.addTab("趋势分析", createTrendAnalysisPanel(trainingName)); // 详细数据标签页 tabbedPane.addTab("详细数据", createDetailedDataPanel(trainingName)); add(tabbedPane); } private JPanel createTrendAnalysisPanel(String trainingName) { JPanel panel = new JPanel(new BorderLayout()); // 趋势分析文本 JTextArea analysisArea = new JTextArea(); analysisArea.setText(HistoryController.getTrendAnalysis(trainingName)); analysisArea.setEditable(false); analysisArea.setLineWrap(true); analysisArea.setWrapStyleWord(true); analysisArea.setFont(new Font("微软雅黑", Font.PLAIN, 16)); panel.add(new JScrollPane(analysisArea), BorderLayout.CENTER); return panel; } private JPanel createDetailedDataPanel(String trainingName) { JPanel panel = new JPanel(new BorderLayout()); // 获取历史数据 List<TrainingRecord> records = HistoryController.getTrainingRecords(trainingName); // 创建得分变化图表 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (TrainingRecord record : records) { dataset.addValue(record.getScore(), "得分", "第" + record.getSession() + "次"); } JFreeChart chart = ChartFactory.createLineChart( "得分变化趋势", "训练次数", "分数", dataset ); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(800, 300)); panel.add(chartPanel, BorderLayout.NORTH); // 创建数据表格 String[] columnNames = {"训练次数", "开始时间", "结束时间", "得分", "评价"}; DefaultTableModel model = new DefaultTableModel(columnNames, 0); for (TrainingRecord record : records) { Object[] rowData = { record.getSession(), record.getStartTime().toString().replace("T", " "), record.getEndTime().toString().replace("T", " "), record.getScore(), record.getEvaluation() }; model.addRow(rowData); } JTable dataTable = new JTable(model); dataTable.setFont(new Font("微软雅黑", Font.PLAIN, 14)); dataTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14)); JScrollPane tableScroll = new JScrollPane(dataTable); panel.add(tableScroll, BorderLayout.CENTER); return panel; } }package view; import controller.AuthController; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginFrame extends JFrame { private JComboBox<String> roleComboBox; private JTextField usernameField; private JPasswordField passwordField; public LoginFrame() { setTitle("AI匹克球系统登录"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10)); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 账号输入 panel.add(new JLabel("账号:")); usernameField = new JTextField(); panel.add(usernameField); // 密码输入 panel.add(new JLabel("密码:")); passwordField = new JPasswordField(); panel.add(passwordField); // 身份选择 panel.add(new JLabel("身份:")); roleComboBox = new JComboBox<>(new String[]{"学生", "教师", "管理员"}); panel.add(roleComboBox); // 登录按钮 JButton loginButton = new JButton("登录"); loginButton.addActionListener(new LoginButtonListener()); panel.add(loginButton); // 密码提示 JLabel hintLabel = new JLabel("* 密码需至少8个字符"); hintLabel.setForeground(Color.GRAY); panel.add(hintLabel); add(panel); } private class LoginButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String username = usernameField.getText(); String password = new String(passwordField.getPassword()); String role = (String) roleComboBox.getSelectedItem(); // 密码长度验证 if (password.length() < 8) { JOptionPane.showMessageDialog(LoginFrame.this, "密码长度需至少8个字符", "错误", JOptionPane.ERROR_MESSAGE); return; } if (AuthController.authenticate(username, password, role)) { dispose(); new StudentMainFrame().setVisible(true); } else { JOptionPane.showMessageDialog(LoginFrame.this, "登录失败,请检查用户名、密码和身份", "错误", JOptionPane.ERROR_MESSAGE); } } } }package view; import controller.AuthController; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class StudentMainFrame extends JFrame { public StudentMainFrame() { setTitle("匹克球训练系统 - " + AuthController.getCurrentUser().getUsername()); setSize(600, 400); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new GridLayout(3, 1, 20, 20)); panel.setBorder(BorderFactory.createEmptyBorder(40, 80, 40, 80)); JButton beginnerBtn = createTrainingButton("初级训练", "匹克球初级训练"); JButton intermediateBtn = createTrainingButton("进阶训练", "匹克球进阶训练"); JButton advancedBtn = createTrainingButton("高阶训练", "匹克球高阶训练"); panel.add(beginnerBtn); panel.add(intermediateBtn); panel.add(advancedBtn); add(panel); } private JButton createTrainingButton(String text, String level) { JButton button = new JButton(text); button.setFont(new Font("微软雅黑", Font.BOLD, 24)); button.addActionListener(e -> { new TrainingSelectionFrame(level).setVisible(true); dispose(); }); return button; } }package view; import controller.AuthController; import controller.TrainingController; import model.TrainingRecord; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TrainingExecutionFrame extends JFrame { private JLabel videoLabel; private JLabel startTimeLabel; private JLabel endTimeLabel; private JLabel scoreLabel; private JLabel evaluationLabel; private JLabel sessionLabel; private TrainingRecord currentRecord; public TrainingExecutionFrame(String trainingName) { setTitle(trainingName); setSize(1000, 700); setLocationRelativeTo(null); // 创建训练记录 currentRecord = new TrainingRecord( AuthController.getCurrentUser().getId(), trainingName, TrainingController.getNextSessionCount(trainingName) ); JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 顶部信息面板 JPanel infoPanel = new JPanel(new GridLayout(1, 3, 10, 10)); sessionLabel = new JLabel("第 " + currentRecord.getSession() + " 次训练"); sessionLabel.setFont(new Font("微软雅黑", Font.BOLD, 18)); sessionLabel.setHorizontalAlignment(SwingConstants.CENTER); infoPanel.add(sessionLabel); JLabel titleLabel = new JLabel(trainingName, SwingConstants.CENTER); titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24)); infoPanel.add(titleLabel); infoPanel.add(new JLabel()); // 占位 mainPanel.add(infoPanel, BorderLayout.NORTH); // 视频区域 videoLabel = new JLabel(); videoLabel.setHorizontalAlignment(SwingConstants.CENTER); videoLabel.setIcon(new ImageIcon("src/main/resources/images/default_training.png")); JScrollPane videoScroll = new JScrollPane(videoLabel); videoScroll.setPreferredSize(new Dimension(640, 480)); mainPanel.add(videoScroll, BorderLayout.CENTER); // 控制面板 JPanel controlPanel = new JPanel(new GridLayout(3, 1, 10, 10)); // 时间面板 JPanel timePanel = new JPanel(new GridLayout(2, 2, 5, 5)); timePanel.add(new JLabel("开始时间:", SwingConstants.RIGHT)); startTimeLabel = new JLabel("--:--:--"); timePanel.add(startTimeLabel); timePanel.add(new JLabel("结束时间:", SwingConstants.RIGHT)); endTimeLabel = new JLabel("--:--:--"); timePanel.add(endTimeLabel); controlPanel.add(timePanel); // 按钮面板 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10)); JButton startBtn = new JButton("开始训练"); JButton stopBtn = new JButton("停止"); JButton saveBtn = new JButton("保存"); JButton deleteBtn = new JButton("删除"); // 设置按钮尺寸 Dimension btnSize = new Dimension(120, 40); startBtn.setPreferredSize(btnSize); stopBtn.setPreferredSize(btnSize); saveBtn.setPreferredSize(btnSize); deleteBtn.setPreferredSize(btnSize); // 添加事件监听 startBtn.addActionListener(new StartButtonListener()); stopBtn.addActionListener(new StopButtonListener()); saveBtn.addActionListener(new SaveButtonListener()); deleteBtn.addActionListener(new DeleteButtonListener()); buttonPanel.add(startBtn); buttonPanel.add(stopBtn); buttonPanel.add(saveBtn); buttonPanel.add(deleteBtn); controlPanel.add(buttonPanel); // 结果面板 JPanel resultPanel = new JPanel(new GridLayout(2, 2, 5, 5)); resultPanel.add(new JLabel("本次训练得分:", SwingConstants.RIGHT)); scoreLabel = new JLabel("--"); resultPanel.add(scoreLabel); resultPanel.add(new JLabel("分析与意见:", SwingConstants.RIGHT)); evaluationLabel = new JLabel("等待分析结果..."); resultPanel.add(evaluationLabel); controlPanel.add(resultPanel); mainPanel.add(controlPanel, BorderLayout.SOUTH); add(mainPanel); } private class StartButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // 记录开始时间 currentRecord.setStartTime(LocalDateTime.now()); startTimeLabel.setText(currentRecord.getStartTime() .format(DateTimeFormatter.ofPattern("yyyy.MM.dd_HH:mm:ss"))); // 模拟启动摄像头 videoLabel.setIcon(new ImageIcon("src/main/resources/images/live_feed.png")); } } private class StopButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // 记录结束时间 currentRecord.setEndTime(LocalDateTime.now()); endTimeLabel.setText(currentRecord.getEndTime() .format(DateTimeFormatter.ofPattern("yyyy.MM.dd_HH:mm:ss"))); // 模拟AI分析结果 currentRecord.setScore((int)(Math.random() * 40 + 60)); // 60-100随机分 currentRecord.setEvaluation("本次训练总体评价较为标准,与标准动作基本一致,值得表扬。"); // 显示结果 scoreLabel.setText(String.valueOf(currentRecord.getScore())); evaluationLabel.setText(currentRecord.getEvaluation()); } } private class SaveButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (currentRecord.getScore() == 0) { JOptionPane.showMessageDialog(TrainingExecutionFrame.this, "请先完成训练并停止录制", "提示", JOptionPane.WARNING_MESSAGE); return; } TrainingController.saveTrainingRecord(currentRecord); JOptionPane.showMessageDialog(TrainingExecutionFrame.this, "训练数据已保存", "成功", JOptionPane.INFORMATION_MESSAGE); } } private class DeleteButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // 重置界面 startTimeLabel.setText("--:--:--"); endTimeLabel.setText("--:--:--"); scoreLabel.setText("--"); evaluationLabel.setText("等待分析结果..."); videoLabel.setIcon(new ImageIcon("src/main/resources/images/default_training.png")); // 重置记录 currentRecord.setStartTime(null); currentRecord.setEndTime(null); currentRecord.setScore(0); currentRecord.setEvaluation(null); } } }package view; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TrainingSelectionFrame extends JFrame { public TrainingSelectionFrame(String trainingLevel) { setTitle(trainingLevel); setSize(800, 600); setLocationRelativeTo(null); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // 添加训练项目 mainPanel.add(createTrainingPanel("握拍姿态训练", "grip_training.png")); mainPanel.add(createTrainingPanel("发球姿态训练", "serve_training.png")); // 可以继续添加更多训练项目 JScrollPane scrollPane = new JScrollPane(mainPanel); add(scrollPane); } private JPanel createTrainingPanel(String title, String imageName) { JPanel panel = new JPanel(new BorderLayout(10, 10)); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 图片 ImageIcon icon = new ImageIcon("src/main/resources/images/" + imageName); JLabel imageLabel = new JLabel(icon); panel.add(imageLabel, BorderLayout.WEST); // 标题 JLabel titleLabel = new JLabel(title, SwingConstants.CENTER); titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24)); panel.add(titleLabel, BorderLayout.CENTER); // 按钮面板 JPanel buttonPanel = new JPanel(new GridLayout(2, 1, 5, 5)); JButton startBtn = new JButton("开始训练"); startBtn.setFont(new Font("微软雅黑", Font.PLAIN, 18)); startBtn.addActionListener(e -> { new TrainingExecutionFrame(title).setVisible(true); dispose(); }); JButton historyBtn = new JButton("历史数据"); historyBtn.setFont(new Font("微软雅黑", Font.PLAIN, 18)); historyBtn.addActionListener(e -> { new HistoryDataFrame(title).setVisible(true); }); buttonPanel.add(startBtn); buttonPanel.add(historyBtn); panel.add(buttonPanel, BorderLayout.EAST); return panel; } }帮我修改代码不使用这种低版本的东西,兼容我的jdk17
06-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值