diff --git a/images/OIP.webp b/images/OIP.webp deleted file mode 100644 index 12d2f19..0000000 Binary files a/images/OIP.webp and /dev/null differ diff --git a/images/巧克力1758715221374.jpg b/images/巧克力1758715221374.jpg new file mode 100644 index 0000000..ef93d51 Binary files /dev/null and b/images/巧克力1758715221374.jpg differ diff --git a/images/水管1758715195119.jpg b/images/水管1758715195119.jpg new file mode 100644 index 0000000..4aa2e25 Binary files /dev/null and b/images/水管1758715195119.jpg differ diff --git a/images/苹果1758714900631.jpg b/images/苹果1758714900631.jpg new file mode 100644 index 0000000..da7f2c1 Binary files /dev/null and b/images/苹果1758714900631.jpg differ diff --git a/images/黑笔1758714930111.jpg b/images/黑笔1758714930111.jpg new file mode 100644 index 0000000..01a44d7 Binary files /dev/null and b/images/黑笔1758714930111.jpg differ diff --git a/images/黑笔1758715260717.jpg b/images/黑笔1758715260717.jpg new file mode 100644 index 0000000..80f633f Binary files /dev/null and b/images/黑笔1758715260717.jpg differ diff --git a/src/main/java/com/example/Home.java b/src/main/java/com/example/Home.java index a8b9768..37ef1e7 100644 --- a/src/main/java/com/example/Home.java +++ b/src/main/java/com/example/Home.java @@ -11,7 +11,8 @@ public class Home extends JFrame implements ActionListener { JMenuBar menuBar; // 库存菜单 进货菜单 销售菜单 - JMenuItem StockMenu,InventoryMenu,SalesMenu,UserMenu; + JButton StockMenu,InventoryMenu,SalesMenu,UserMenu; + private String userIdentity; class BackgroundPanel extends JPanel { private Image bg; public BackgroundPanel(String path) { @@ -33,9 +34,9 @@ public class Home extends JFrame implements ActionListener { setContentPane(bgPanel); menuBar = new JMenuBar(); - StockMenu = new JMenuItem("库存信息管理"); - InventoryMenu = new JMenuItem("进货信息管理"); - SalesMenu = new JMenuItem("销售信息管理"); + StockMenu = new JButton("库存信息管理"); + InventoryMenu = new JButton("进货信息管理"); + SalesMenu = new JButton("销售信息管理"); menuBar.add(StockMenu); menuBar.add(InventoryMenu); menuBar.add(SalesMenu); @@ -48,13 +49,13 @@ public class Home extends JFrame implements ActionListener { try { ResultSet rs = jdbc.query(sql); if(rs.next()){ - username = rs.getString("identity"); + userIdentity = rs.getString("identity"); } } catch (SQLException e) { throw new RuntimeException(e); } - if(username.equals("admin")){ - UserMenu = new JMenuItem("用户管理"); + if(userIdentity.equals("admin")){ + UserMenu = new JButton("用户管理"); menuBar.add(UserMenu); UserMenu.addActionListener(this); } @@ -72,7 +73,7 @@ public class Home extends JFrame implements ActionListener { new InventoryProductManagement(); } if(e.getSource()==SalesMenu){ - new SalesProductManagement(); + new SalesProductManagement(userIdentity); } if(e.getSource()==UserMenu){ new UserManagement(); diff --git a/src/main/java/com/example/InventoryProductManagement.java b/src/main/java/com/example/InventoryProductManagement.java index d5e17ee..d0cfe72 100644 --- a/src/main/java/com/example/InventoryProductManagement.java +++ b/src/main/java/com/example/InventoryProductManagement.java @@ -2,184 +2,263 @@ package com.example; import javax.swing.*; import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.sql.ResultSet; import java.sql.SQLException; public class InventoryProductManagement extends JFrame implements ActionListener { - JMenuBar menuBar;//创建主菜单栏容器 - JMenu menu;//创建顶级菜单项“菜单” - JMenuItem menuItem1,menuItem2,menuItem3;//创建菜单子项(添加/删除商品) - private JTable table;//表格组件,用于展示商品数据 - private DefaultTableModel tableModel;//表格数据模型 - InventoryProductManagement() { - super("进货信息管理");//设置窗口标题 - menuBar = new JMenuBar();//实例化菜单栏 - setJMenuBar(menuBar);//将菜单栏添加到窗体顶部 - menu = new JMenu("菜单");//创建顶级菜单“菜单” - menuBar.add(menu);//将菜单添加到菜单栏 - //创建菜单项 - menuItem1 = new JMenuItem("进货"); - menuItem2 = new JMenuItem("删除"); - menuItem3 = new JMenuItem("帮助"); - //添加菜单项到菜单 - menu.add(menuItem1); - menu.add(menuItem2); - menu.add(menuItem3); -// menu.add(menuItem3); - //注册菜单项点击监听器(this表示当前类处理事件) - menuItem1.addActionListener(this); - menuItem2.addActionListener(this); - menuItem3.addActionListener(this); -// menuItem3.addActionListener(this); - setSize(500,500);//设置窗口大小 - setLocationRelativeTo(null);//窗口居中显示 - // 表格初始化 - String[] columnNames = {"商品名称(种类)", "商品数量(件)", "进货单价(元)"};//定义表头,此处更改表头文字展示 - tableModel = new DefaultTableModel(columnNames, 0);//创建空表格模型 - table = new JTable(tableModel);//基于模型创建表格 + private JMenuBar menuBar; + private JMenuItem menuItemAdd, menuItemDelete; + private JTable table; + private DefaultTableModel tableModel; + private String selectedImagePath = null; + + public InventoryProductManagement() { + super("进货信息管理"); + menuBar = new JMenuBar(); + setJMenuBar(menuBar); + + menuItemAdd = new JMenuItem("进货"); + menuItemDelete = new JMenuItem("删除"); + menuBar.add(menuItemAdd); + menuBar.add(menuItemDelete); + + menuItemAdd.addActionListener(this); + menuItemDelete.addActionListener(this); + + setSize(600, 500); + setLocationRelativeTo(null); + + // 表格初始化 + String[] columnNames = {"商品照片","商品名称","商品类别","商品数量(件)","进货单价(元)"}; + tableModel = new DefaultTableModel(columnNames, 0) { + @Override + public Class getColumnClass(int column) { + if (column == 0) return Icon.class; + return super.getColumnClass(column); + } + + @Override + public boolean isCellEditable(int row, int column) { + return false; + } + }; + + table = new JTable(tableModel); + table.setRowHeight(60); // 设置行高以显示图片 + + // 自定义图片单元格渲染 + table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() { + JLabel label = new JLabel(); + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + label.setHorizontalAlignment(JLabel.CENTER); + label.setIcon((Icon) value); + return label; + } + }); - // 添加带滚动条的表格面板到窗口中央 JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); - - // 初始化加载数据库数据 - loadData();//加载数据库数据到表格 - setVisible(true);//显示窗口 + loadData(); // 初始化加载数据 + setVisible(true); } + // 加载数据库数据 private void loadData() { - Jdbc jdbc = new Jdbc();//创建数据库连接对象 + Jdbc jdbc = new Jdbc(); try { - //执行SQL查询(获取商品名称/库存/进阶/售价/利润/销量) - ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold FROM commodity"); - // 清空旧数据 - tableModel.setRowCount(0);//清空表格现有数据 - // 填充新数据(遍历查询结果) + ResultSet rs = jdbc.query("SELECT name, type, count, purchase_price, image_path FROM commodity"); + tableModel.setRowCount(0); // 清空表格 while (rs.next()) { - //构建表格行数据(只显示名称/库存/进阶) - Object[] row = { - rs.getString("name"), - rs.getInt("count"), - rs.getDouble("purchase_price"), - }; - tableModel.addRow(row);//添加数据行到表格 + String name = rs.getString("name"); + String type = rs.getString("type"); + int count = rs.getInt("count"); + double price = rs.getDouble("purchase_price"); + String imagePath = rs.getString("image_path"); + + ImageIcon icon = null; + if (imagePath != null && !imagePath.isEmpty()) { + File imgFile = new File("images/" + imagePath); + if (imgFile.exists()) { + icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath()) + .getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH)); + } + } + + Object[] row = {icon, name, type, count, price}; + tableModel.addRow(row); } - rs.close();//关闭结果集 - jdbc.close();//关闭数据库连接 + rs.close(); + jdbc.close(); } catch (SQLException e) { e.printStackTrace(); - JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());//弹出错误提示 + JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage()); } } @Override public void actionPerformed(ActionEvent e) { - if (e.getSource() == menuItem1) { - JFrame frame = new JFrame();//创建添加窗口 - frame.setTitle("添加商品"); - frame.setLayout(new GridLayout(4, 2));//四行两列网格布局 - //创建输入组件 - JLabel nameLabel = new JLabel("商品名称:"); - JTextField nameField = new JTextField(); - JLabel countLabel = new JLabel("商品数量:"); - JTextField countField = new JTextField(); - JLabel purchasePriceLabel = new JLabel("进货单价:"); - JTextField purchasePriceField = new JTextField(); - //添加按钮和取消按钮 - JButton addButton = new JButton("添加"); - JButton cancelButton = new JButton("取消"); - //将组件添加到窗口 - frame.add(nameLabel); - frame.add(nameField); - frame.add(countLabel); - frame.add(countField); - frame.add(purchasePriceLabel); - frame.add(purchasePriceField); - frame.add(addButton); - frame.add(cancelButton); - //添加按钮事件 - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - //获取输入值 - String name = nameField.getText(); - int count = Integer.parseInt(countField.getText()); - double purchasePrice = Double.parseDouble(purchasePriceField.getText()); - // 调用数据库添加方法 执行SQL插入(初始化销量为0) - Jdbc jdbc = new Jdbc(); - try { - jdbc.update("INSERT INTO commodity (name, count, purchase_price, quantity_sold) VALUES ('" + name + "', " + count + ", " + purchasePrice + ", " + 0 + ");"); - jdbc.close(); - // 刷新数据 - loadData();//刷新表格数据 - // 关闭弹窗 - frame.dispose();//关闭添加窗口 - } catch (SQLException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(frame, "添加商品失败: " + ex.getMessage()); - } - } - }); - cancelButton.addActionListener(new ActionListener() {//取消按钮事件 - @Override - public void actionPerformed(ActionEvent e) { - frame.dispose(); - } - }); - frame.setSize(300, 200); - frame.setLocationRelativeTo(null); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setVisible(true); - } - else if (e.getSource() == menuItem2) { - JFrame frame = new JFrame();//创建删除窗口 - frame.setTitle("删除商品"); - frame.setLayout(new GridLayout(2, 2)); - JLabel nameLabel = new JLabel("商品名称:"); - JTextField nameField = new JTextField(); - JButton deleteButton = new JButton("删除"); - JButton cancelButton = new JButton("取消"); - frame.add(nameLabel); - frame.add(nameField); - frame.add(deleteButton); - frame.add(cancelButton); - //删除按钮事件 - deleteButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String name = nameField.getText();//获取要删除的商品名 - // 调用数据库删除方法 - Jdbc jdbc = new Jdbc(); - try { - //执行SQL删除 - jdbc.update("DELETE FROM commodity WHERE name='" + name + "'"); - jdbc.close(); - // 刷新表格 - loadData(); - // 关闭弹窗 - frame.dispose(); - } catch (SQLException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(frame, "删除商品失败: " + ex.getMessage()); - } - } - }); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - frame.dispose(); - } - }); - frame.setSize(300, 200); - frame.setLocationRelativeTo(null); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setVisible(true); + if (e.getSource() == menuItemAdd) { + showAddProductWindow(); + } else if (e.getSource() == menuItemDelete) { + showDeleteProductWindow(); } } + + private void showAddProductWindow() { + JFrame frame = new JFrame("添加商品"); + frame.setLayout(new GridLayout(6,2)); + + JLabel nameLabel = new JLabel("商品名称:"); + JTextField nameField = new JTextField(); + + JLabel countLabel = new JLabel("商品数量:"); + JTextField countField = new JTextField(); + + JLabel purchasePriceLabel = new JLabel("进货单价:"); + JTextField purchasePriceField = new JTextField(); + + JLabel typeLabel = new JLabel("商品类别:"); + String[] categories = {"食品","生活用品","娱乐物品","学习物品","其他物品"}; + JComboBox typeComboBox = new JComboBox<>(categories); + + JLabel imageLabel = new JLabel("商品图片:"); + JButton chooseImageButton = new JButton("选择图片"); + + JButton addButton = new JButton("添加"); + JButton cancelButton = new JButton("取消"); + + frame.add(nameLabel); frame.add(nameField); + frame.add(countLabel); frame.add(countField); + frame.add(purchasePriceLabel); frame.add(purchasePriceField); + frame.add(typeLabel); frame.add(typeComboBox); + frame.add(imageLabel); frame.add(chooseImageButton); + frame.add(addButton); frame.add(cancelButton); + + // 图片选择事件 + chooseImageButton.addActionListener(ev -> { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("选择商品图片"); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + int result = fileChooser.showOpenDialog(frame); + if(result == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + selectedImagePath = selectedFile.getAbsolutePath(); + JOptionPane.showMessageDialog(frame, "已选择图片: " + selectedFile.getName()); + } + }); + + // 添加按钮事件 + addButton.addActionListener(ev -> { + String name = nameField.getText(); + int count; + double purchasePrice; + try { + count = Integer.parseInt(countField.getText()); + purchasePrice = Double.parseDouble(purchasePriceField.getText()); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(frame, "数量和价格必须为数字"); + return; + } + String type = (String) typeComboBox.getSelectedItem(); + String savedImageFileName = null; + + if(selectedImagePath != null) { + try { + File imageDir = new File("images"); + if(!imageDir.exists()) imageDir.mkdir(); + String extension = selectedImagePath.substring(selectedImagePath.lastIndexOf(".")); + savedImageFileName = name + System.currentTimeMillis() + extension; + Path targetPath = Paths.get("images", savedImageFileName); + Files.copy(Paths.get(selectedImagePath), targetPath, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ex) { + ex.printStackTrace(); + JOptionPane.showMessageDialog(frame, "图片保存失败: " + ex.getMessage()); + return; + } + } + + Jdbc jdbc = new Jdbc(); + try { + String sql = "INSERT INTO commodity (name, count, purchase_price, quantity_sold, type, image_path) " + + "VALUES ('"+name+"', "+count+", "+purchasePrice+", 0, '"+type+"', '"+(savedImageFileName != null ? savedImageFileName : "")+"');"; + jdbc.update(sql); + jdbc.close(); + loadData(); + frame.dispose(); + } catch (SQLException ex) { + ex.printStackTrace(); + JOptionPane.showMessageDialog(frame,"添加商品失败: "+ex.getMessage()); + } + }); + + cancelButton.addActionListener(ev -> frame.dispose()); + + frame.setSize(400, 300); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setVisible(true); + } + + private void showDeleteProductWindow() { + JFrame frame = new JFrame("删除商品"); + frame.setLayout(new GridLayout(2,2)); + JLabel nameLabel = new JLabel("商品名称:"); + JTextField nameField = new JTextField(); + JButton deleteButton = new JButton("删除"); + JButton cancelButton = new JButton("取消"); + frame.add(nameLabel); frame.add(nameField); + frame.add(deleteButton); frame.add(cancelButton); + + deleteButton.addActionListener(ev -> { + String name = nameField.getText(); + Jdbc jdbc = new Jdbc(); + try { + // 查询要删除的图片路径 + ResultSet rs = jdbc.query("SELECT image_path FROM commodity WHERE name='"+name+"'"); + String imagePath = null; + if(rs.next()) { + imagePath = rs.getString("image_path"); + } + rs.close(); + + // 删除数据库记录 + jdbc.update("DELETE FROM commodity WHERE name='"+name+"'"); + jdbc.close(); + + // 删除图片文件 + if(imagePath != null && !imagePath.isEmpty()) { + File imgFile = new File("images/"+imagePath); + if(imgFile.exists()) imgFile.delete(); + } + + loadData(); + frame.dispose(); + } catch (SQLException ex) { + ex.printStackTrace(); + JOptionPane.showMessageDialog(frame, "删除商品失败: "+ex.getMessage()); + } + }); + + cancelButton.addActionListener(ev -> frame.dispose()); + + frame.setSize(300,200); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setVisible(true); + } + public static void main(String[] args) { - new InventoryProductManagement();//启动应用程序 + SwingUtilities.invokeLater(InventoryProductManagement::new); } } diff --git a/src/main/java/com/example/SalesProductManagement.java b/src/main/java/com/example/SalesProductManagement.java index 6466a49..ce2e9f5 100644 --- a/src/main/java/com/example/SalesProductManagement.java +++ b/src/main/java/com/example/SalesProductManagement.java @@ -1,127 +1,151 @@ package com.example; import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; +import java.io.File; import java.sql.ResultSet; -import java.sql.SQLException; -public class SalesProductManagement extends JFrame implements ActionListener { +public class SalesProductManagement extends JFrame { + private JTable table; private DefaultTableModel tableModel; - private JTextField idField, nameField, phoneField, addressField; - private JButton addBtn; + private JTextField totalField; + private JButton checkoutBtn; + private String userIdentity; // 当前用户身份 - public SalesProductManagement() { + public SalesProductManagement(String identity) { + this.userIdentity = identity; - setTitle("商品信息管理"); - setSize(800, 600); + setTitle("商品销售信息管理"); + setSize(900, 600); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - // 创建主面板 JPanel mainPanel = new JPanel(new BorderLayout()); - // 创建表格面板 - JPanel tablePanel = new JPanel(new BorderLayout()); - tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + // 表格 + String[] columnNames = {"商品图片","名称","类别","单价","购买数量"}; + tableModel = new DefaultTableModel(columnNames,0){ + @Override + public boolean isCellEditable(int row, int column){ + if(column == 3) return "admin".equals(userIdentity); // 单价列 admin 可编辑 + return column == 4; // 购买数量列所有用户可编辑 + } - // 创建表格模型 - String[] columnNames = {"名称", "单价", "购买数量"}; - tableModel = new DefaultTableModel(columnNames, 0); + @Override + public Class getColumnClass(int column){ + if(column==0) return Icon.class; + if(column==3) return Double.class; + if(column==4) return Integer.class; + return String.class; + } + }; table = new JTable(tableModel); - table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); - table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14)); - table.setRowHeight(25); + table.setRowHeight(60); + + // 图片渲染器 + table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() { + JLabel label = new JLabel(); + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){ + label.setHorizontalAlignment(JLabel.CENTER); + label.setIcon((Icon)value); + return label; + } + }); - // 添加滚动面板 JScrollPane scrollPane = new JScrollPane(table); - tablePanel.add(scrollPane, BorderLayout.CENTER); + mainPanel.add(scrollPane, BorderLayout.CENTER); - // 创建输入面板 - JPanel inputPanel = new JPanel(new GridLayout(1, 2, 10, 10)); - inputPanel.setBorder(BorderFactory.createTitledBorder("结算信息")); - inputPanel.setFont(new Font("微软雅黑", Font.PLAIN, 14)); - - addBtn = new JButton("结算"); - addBtn.addActionListener(this); - - - inputPanel.add(addBtn); - - inputPanel.add(new JLabel("共计:")); - addressField = new JTextField(); - inputPanel.add(addressField); - - - - - // 组装面板 - mainPanel.add(tablePanel, BorderLayout.CENTER); - mainPanel.add(inputPanel, BorderLayout.SOUTH); + // 结算面板 + JPanel checkoutPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,10)); + checkoutBtn = new JButton("结算"); + totalField = new JTextField(10); + totalField.setEditable(false); + checkoutPanel.add(new JLabel("总金额:")); + checkoutPanel.add(totalField); + checkoutPanel.add(checkoutBtn); + mainPanel.add(checkoutPanel, BorderLayout.SOUTH); add(mainPanel); loadData(); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + checkoutBtn.addActionListener(e -> calculateTotal()); + + // 监听单元格变化,修改后立即更新数据库 + tableModel.addTableModelListener(e -> { + if(e.getType() == TableModelEvent.UPDATE){ + int row = e.getFirstRow(); + int col = e.getColumn(); + String name = tableModel.getValueAt(row,1).toString(); // 商品名称 + try{ + Jdbc jdbc = new Jdbc(); + if(col == 3 && "admin".equals(userIdentity)){ // 单价 + double price = Double.parseDouble(tableModel.getValueAt(row,3).toString()); + jdbc.update("UPDATE commodity SET selling_price="+price+" WHERE name='"+name+"'"); + } else if(col == 4){ // 购买数量 + int quantity = Integer.parseInt(tableModel.getValueAt(row,4).toString()); + jdbc.update("UPDATE commodity SET quantity_sold="+quantity+" WHERE name='"+name+"'"); + } + jdbc.close(); + }catch(Exception ex){ + ex.printStackTrace(); + JOptionPane.showMessageDialog(this,"更新数据库失败: "+ex.getMessage()); + } + } + }); + setVisible(true); - } - //主类,调试 - public static void main(String[] args) { - new SalesProductManagement(); - } - - - - private void loadData() { + private void loadData(){ Jdbc jdbc = new Jdbc(); - try { - ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold FROM commodity"); - // 清空旧数据 + try{ + ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold,type,image_path FROM commodity"); tableModel.setRowCount(0); - // 填充新数据 - while (rs.next()) { - Object[] row = { - rs.getString("name"), - rs.getDouble("selling_price"), - rs.getInt("quantity_sold"), - }; + while(rs.next()){ + String name = rs.getString("name"); + double price = rs.getDouble("selling_price"); + int quantity = rs.getInt("quantity_sold"); + String type = rs.getString("type"); + String imagePath = rs.getString("image_path"); + + ImageIcon icon = null; + if(imagePath!=null && !imagePath.isEmpty()){ + File imgFile = new File("images/"+imagePath); + if(imgFile.exists()){ + icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath()) + .getImage().getScaledInstance(50,50,Image.SCALE_SMOOTH)); + } + } + + Object[] row = {icon,name,type,price,quantity}; tableModel.addRow(row); } rs.close(); jdbc.close(); - } catch (SQLException e) { + }catch(Exception e){ e.printStackTrace(); - JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage()); + JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage()); } } - @Override - public void actionPerformed(ActionEvent e) { - if(e.getSource() == addBtn) { - double total = 0.0; // 总金额 - - // 获取表格的行数 - int rowCount = tableModel.getRowCount(); - - // 遍历每一行数据 - for(int i = 0; i < rowCount; i++) { - // 获取单价(第1列,索引从0开始) - double price = (double) tableModel.getValueAt(i, 1); - // 获取数量(第2列) - int quantity = (int) tableModel.getValueAt(i, 2); - - // 计算该行的金额并累加到总金额 - total += price * quantity; - } - - // 在文本框中显示总金额 - addressField.setText(String.format("%.2f", total) + " 元"); + private void calculateTotal(){ + double total = 0.0; + for(int i=0;i getColumnClass(int column) { + if(column == 0) return Icon.class; // 图片列 + return super.getColumnClass(column); } }; table = new JTable(tableModel); + table.setRowHeight(60); - // 监听单元格编辑完成事件,自动更新数据库 + // 图片渲染器 + table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() { + JLabel label = new JLabel(); + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + label.setHorizontalAlignment(JLabel.CENTER); + label.setIcon((Icon)value); + return label; + } + }); + + // 销售数量编辑事件 table.getModel().addTableModelListener(e -> { int row = e.getFirstRow(); int column = e.getColumn(); - - if (column == 5) { // 销售数量列 - String name = (String) tableModel.getValueAt(row, 0); // 商品名称 + if(column == 7) { // 销售数量列 + String name = (String)tableModel.getValueAt(row, 1); Object value = tableModel.getValueAt(row, column); - - if (value != null && !value.toString().trim().isEmpty()) { + if(value != null && !value.toString().trim().isEmpty()) { try { int quantitySold = Integer.parseInt(value.toString().trim()); Jdbc jdbc = new Jdbc(); @@ -64,143 +84,188 @@ public class StockProductManagement extends JFrame implements ActionListener { } }); - - // 滚动面板 JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); - // 初始化加载数据库数据 loadData(); setVisible(true); } + @Override - public void actionPerformed(ActionEvent e) { - if (e.getSource() == menuItem1) { - JFrame frame = new JFrame(); - frame.setTitle("添加商品"); - frame.setLayout(new GridLayout(5, 2)); - JLabel nameLabel = new JLabel("商品名称:"); - JTextField nameField = new JTextField(); - JLabel countLabel = new JLabel("商品数量:"); - JTextField countField = new JTextField(); - JLabel purchasePriceLabel = new JLabel("进货单价:"); - JTextField purchasePriceField = new JTextField(); - JLabel sellingPriceLabel = new JLabel("销售单价:"); - JTextField sellingPriceField = new JTextField(); - JButton addButton = new JButton("添加"); - JButton cancelButton = new JButton("取消"); - frame.add(nameLabel); - frame.add(nameField); - frame.add(countLabel); - frame.add(countField); - frame.add(purchasePriceLabel); - frame.add(purchasePriceField); - frame.add(sellingPriceLabel); - frame.add(sellingPriceField); - frame.add(addButton); - frame.add(cancelButton); - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String name = nameField.getText(); - int count = Integer.parseInt(countField.getText()); - double purchasePrice = Double.parseDouble(purchasePriceField.getText()); - double sellingPrice = Double.parseDouble(sellingPriceField.getText()); - // 调用数据库添加方法 - Jdbc jdbc = new Jdbc(); - try { - jdbc.update("INSERT INTO commodity (name, count, purchase_price, selling_price, profit) VALUES ('" + name + "', " + count + ", " + purchasePrice + ", " + sellingPrice + ", " + (sellingPrice - purchasePrice) + ", 0);"); - jdbc.close(); - // 刷新数据 - loadData(); - // 关闭弹窗 - frame.dispose(); - } catch (SQLException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(frame, "添加商品失败: " + ex.getMessage()); - } - } - }); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - frame.dispose(); - } - }); - frame.setSize(300, 200); - setLocationRelativeTo(null); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setVisible(true); - } - else if (e.getSource() == menuItem2) { - JFrame frame = new JFrame(); - frame.setTitle("删除商品"); - frame.setLayout(new GridLayout(2, 2)); - JLabel nameLabel = new JLabel("商品名称:"); - JTextField nameField = new JTextField(); - JButton deleteButton = new JButton("删除"); - JButton cancelButton = new JButton("取消"); - frame.add(nameLabel); - frame.add(nameField); - frame.add(deleteButton); - frame.add(cancelButton); - deleteButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String name = nameField.getText(); - // 调用数据库删除方法 - Jdbc jdbc = new Jdbc(); - try { - jdbc.update("DELETE FROM commodity WHERE name='" + name + "'"); - jdbc.close(); - // 刷新数据 - loadData(); - // 关闭弹窗 - frame.dispose(); - } catch (SQLException ex) { - ex.printStackTrace(); - JOptionPane.showMessageDialog(frame, "删除商品失败: " + ex.getMessage()); - } - } - }); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - frame.dispose(); - } - }); - frame.setSize(300, 200); - setLocationRelativeTo(null); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setVisible(true); + public void actionPerformed(java.awt.event.ActionEvent e) { + if(e.getSource() == menuItemAdd){ + showAddProductWindow(); + } else if(e.getSource() == menuItemDelete){ + deleteSelectedProduct(); } } - private void loadData() { + private void showAddProductWindow(){ + JFrame frame = new JFrame("添加商品"); + frame.setLayout(new GridLayout(7,2)); + + JLabel nameLabel = new JLabel("商品名称:"); + JTextField nameField = new JTextField(); + JLabel countLabel = new JLabel("商品数量:"); + JTextField countField = new JTextField(); + JLabel purchasePriceLabel = new JLabel("进货单价:"); + JTextField purchasePriceField = new JTextField(); + JLabel sellingPriceLabel = new JLabel("销售单价:"); + JTextField sellingPriceField = new JTextField(); + + JLabel typeLabel = new JLabel("商品类别:"); + String[] categories = {"食品","生活用品","娱乐物品","学习物品","其他物品"}; + JComboBox typeComboBox = new JComboBox<>(categories); + + JLabel imageLabel = new JLabel("商品图片:"); + JButton chooseImageButton = new JButton("选择图片"); + + JButton addButton = new JButton("添加"); + JButton cancelButton = new JButton("取消"); + + frame.add(nameLabel); frame.add(nameField); + frame.add(countLabel); frame.add(countField); + frame.add(purchasePriceLabel); frame.add(purchasePriceField); + frame.add(sellingPriceLabel); frame.add(sellingPriceField); + frame.add(typeLabel); frame.add(typeComboBox); + frame.add(imageLabel); frame.add(chooseImageButton); + frame.add(addButton); frame.add(cancelButton); + + chooseImageButton.addActionListener(ev -> { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("选择商品图片"); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + int result = fileChooser.showOpenDialog(frame); + if(result == JFileChooser.APPROVE_OPTION){ + File selectedFile = fileChooser.getSelectedFile(); + selectedImagePath = selectedFile.getAbsolutePath(); + JOptionPane.showMessageDialog(frame, "已选择图片: " + selectedFile.getName()); + } + }); + + addButton.addActionListener(ev -> { + String name = nameField.getText(); + int count; + double purchasePrice, sellingPrice; + String type = (String) typeComboBox.getSelectedItem(); + + try { + count = Integer.parseInt(countField.getText()); + purchasePrice = Double.parseDouble(purchasePriceField.getText()); + sellingPrice = Double.parseDouble(sellingPriceField.getText()); + } catch(NumberFormatException ex){ + JOptionPane.showMessageDialog(frame, "数量和价格必须为数字"); + return; + } + + String savedImageFileName = null; + if(selectedImagePath != null){ + try{ + File imageDir = new File("images"); + if(!imageDir.exists()) imageDir.mkdir(); + String extension = selectedImagePath.substring(selectedImagePath.lastIndexOf(".")); + savedImageFileName = name + System.currentTimeMillis() + extension; + Path targetPath = Paths.get("images", savedImageFileName); + Files.copy(Paths.get(selectedImagePath), targetPath, StandardCopyOption.REPLACE_EXISTING); + }catch(IOException ex){ + ex.printStackTrace(); + JOptionPane.showMessageDialog(frame, "图片保存失败: "+ex.getMessage()); + return; + } + } + + Jdbc jdbc = new Jdbc(); + try{ + String sql = "INSERT INTO commodity (name, count, purchase_price, selling_price, profit, quantity_sold, type, image_path) " + + "VALUES ('"+name+"', "+count+", "+purchasePrice+", "+sellingPrice+", "+(sellingPrice-purchasePrice)+", 0, '"+type+"', '"+(savedImageFileName!=null?savedImageFileName:"")+"')"; + jdbc.update(sql); + jdbc.close(); + loadData(); + frame.dispose(); + }catch(Exception ex){ + ex.printStackTrace(); + JOptionPane.showMessageDialog(frame, "添加商品失败: "+ex.getMessage()); + } + }); + + cancelButton.addActionListener(ev -> frame.dispose()); + + frame.setSize(450,400); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setVisible(true); + } + + private void deleteSelectedProduct() { + int selectedRow = table.getSelectedRow(); + if(selectedRow == -1){ + JOptionPane.showMessageDialog(this, "请先选中要删除的商品行"); + return; + } + + String name = (String)tableModel.getValueAt(selectedRow,1); // 商品名称 + int confirm = JOptionPane.showConfirmDialog(this,"确定删除商品 \"" + name + "\" 吗?","确认删除",JOptionPane.YES_NO_OPTION); + if(confirm != JOptionPane.YES_OPTION) return; + + // 删除数据库和图片 Jdbc jdbc = new Jdbc(); - try { - ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold FROM commodity"); - // 清空旧数据 + try{ + ResultSet rs = jdbc.query("SELECT image_path FROM commodity WHERE name='"+name+"'"); + String imagePath = null; + if(rs.next()) imagePath = rs.getString("image_path"); + rs.close(); + + jdbc.update("DELETE FROM commodity WHERE name='"+name+"'"); + jdbc.close(); + + if(imagePath != null && !imagePath.isEmpty()){ + File imgFile = new File("images/"+imagePath); + if(imgFile.exists()) imgFile.delete(); + } + + loadData(); + }catch(Exception ex){ + ex.printStackTrace(); + JOptionPane.showMessageDialog(this, "删除商品失败: "+ex.getMessage()); + } + } + + private void loadData(){ + Jdbc jdbc = new Jdbc(); + try{ + ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold,type,image_path FROM commodity"); tableModel.setRowCount(0); - // 填充新数据 - while (rs.next()) { - Object[] row = { - rs.getString("name"), - rs.getInt("count"), - rs.getDouble("purchase_price"), - rs.getDouble("selling_price"), - rs.getDouble("profit"), - }; + while(rs.next()){ + String name = rs.getString("name"); + int count = rs.getInt("count"); + double purchasePrice = rs.getDouble("purchase_price"); + double sellingPrice = rs.getDouble("selling_price"); + double profit = rs.getDouble("profit"); + String quantitySold = rs.getString("quantity_sold"); + String type = rs.getString("type"); + String imagePath = rs.getString("image_path"); + + ImageIcon icon = null; + if(imagePath!=null && !imagePath.isEmpty()){ + File imgFile = new File("images/"+imagePath); + if(imgFile.exists()){ + icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath()) + .getImage().getScaledInstance(50,50,Image.SCALE_SMOOTH)); + } + } + + Object[] row = {icon,name,type,count,purchasePrice,sellingPrice,profit,quantitySold}; tableModel.addRow(row); } rs.close(); jdbc.close(); - } catch (SQLException e) { + }catch(Exception e){ e.printStackTrace(); - JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage()); + JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage()); } } - public static void main(String[] args) { - new StockProductManagement(); + + public static void main(String[] args){ + SwingUtilities.invokeLater(StockProductManagement::new); } } diff --git a/src/main/java/com/example/UserManagement.java b/src/main/java/com/example/UserManagement.java index bd88b24..951cae9 100644 --- a/src/main/java/com/example/UserManagement.java +++ b/src/main/java/com/example/UserManagement.java @@ -85,7 +85,7 @@ public class UserManagement extends JFrame implements ActionListener { // 添加用户 if (e.getSource() == addItem) { JFrame frame = new JFrame("添加用户"); - frame.setLayout(new GridLayout(5, 2)); + frame.setLayout(new GridLayout(3, 2)); JLabel nameLabel = new JLabel("用户名:"); JTextField nameField = new JTextField(); JLabel passLabel = new JLabel("密码:"); @@ -150,29 +150,26 @@ public class UserManagement extends JFrame implements ActionListener { String oldUsername = (String) tableModel.getValueAt(row, 0); JFrame frame = new JFrame("修改用户"); - frame.setLayout(new GridLayout(5, 2)); + frame.setLayout(new GridLayout(4, 2)); JTextField nameField = new JTextField((String) tableModel.getValueAt(row, 0)); JTextField passField = new JTextField((String) tableModel.getValueAt(row, 1)); - JTextField emailField = new JTextField((String) tableModel.getValueAt(row, 2)); - JTextField phoneField = new JTextField((String) tableModel.getValueAt(row, 3)); + JTextField identityField = new JTextField((String) tableModel.getValueAt(row, 2)); JButton saveButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); frame.add(new JLabel("用户名:")); frame.add(nameField); frame.add(new JLabel("密码:")); frame.add(passField); - frame.add(new JLabel("邮箱:")); frame.add(emailField); - frame.add(new JLabel("电话:")); frame.add(phoneField); + frame.add(new JLabel("身份:")); frame.add(identityField); frame.add(saveButton); frame.add(cancelButton); saveButton.addActionListener(ev -> { String username = nameField.getText(); String password = passField.getText(); - String email = emailField.getText(); - String phone = phoneField.getText(); + String identity = identityField.getText(); Jdbc jdbc = new Jdbc(); try { - jdbc.update("UPDATE user SET username='" + username + "', password='" + password + "', email='" + email + "', phone='" + phone + "' WHERE username='" + oldUsername + "'"); + jdbc.update("UPDATE user SET username='" + username + "', password='" + password + "', identity='" + identity + "' WHERE username='" + oldUsername + "'"); jdbc.close(); loadData(); frame.dispose();