列表显示图片,添加时添加图片,物品分类别

This commit is contained in:
lu
2025-09-24 20:33:06 +08:00
parent 12b7b88198
commit 2f386d22a6
11 changed files with 568 additions and 402 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -11,7 +11,8 @@ public class Home extends JFrame implements ActionListener {
JMenuBar menuBar; JMenuBar menuBar;
// 库存菜单 进货菜单 销售菜单 // 库存菜单 进货菜单 销售菜单
JMenuItem StockMenu,InventoryMenu,SalesMenu,UserMenu; JButton StockMenu,InventoryMenu,SalesMenu,UserMenu;
private String userIdentity;
class BackgroundPanel extends JPanel { class BackgroundPanel extends JPanel {
private Image bg; private Image bg;
public BackgroundPanel(String path) { public BackgroundPanel(String path) {
@@ -33,9 +34,9 @@ public class Home extends JFrame implements ActionListener {
setContentPane(bgPanel); setContentPane(bgPanel);
menuBar = new JMenuBar(); menuBar = new JMenuBar();
StockMenu = new JMenuItem("库存信息管理"); StockMenu = new JButton("库存信息管理");
InventoryMenu = new JMenuItem("进货信息管理"); InventoryMenu = new JButton("进货信息管理");
SalesMenu = new JMenuItem("销售信息管理"); SalesMenu = new JButton("销售信息管理");
menuBar.add(StockMenu); menuBar.add(StockMenu);
menuBar.add(InventoryMenu); menuBar.add(InventoryMenu);
menuBar.add(SalesMenu); menuBar.add(SalesMenu);
@@ -48,13 +49,13 @@ public class Home extends JFrame implements ActionListener {
try { try {
ResultSet rs = jdbc.query(sql); ResultSet rs = jdbc.query(sql);
if(rs.next()){ if(rs.next()){
username = rs.getString("identity"); userIdentity = rs.getString("identity");
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if(username.equals("admin")){ if(userIdentity.equals("admin")){
UserMenu = new JMenuItem("用户管理"); UserMenu = new JButton("用户管理");
menuBar.add(UserMenu); menuBar.add(UserMenu);
UserMenu.addActionListener(this); UserMenu.addActionListener(this);
} }
@@ -72,7 +73,7 @@ public class Home extends JFrame implements ActionListener {
new InventoryProductManagement(); new InventoryProductManagement();
} }
if(e.getSource()==SalesMenu){ if(e.getSource()==SalesMenu){
new SalesProductManagement(); new SalesProductManagement(userIdentity);
} }
if(e.getSource()==UserMenu){ if(e.getSource()==UserMenu){
new UserManagement(); new UserManagement();

View File

@@ -2,184 +2,263 @@ package com.example;
import javax.swing.*; import javax.swing.*;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 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.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InventoryProductManagement extends JFrame implements ActionListener { public class InventoryProductManagement extends JFrame implements ActionListener {
JMenuBar menuBar;//创建主菜单栏容器 private JMenuBar menuBar;
JMenu menu;//创建顶级菜单项“菜单” private JMenuItem menuItemAdd, menuItemDelete;
JMenuItem menuItem1,menuItem2,menuItem3;//创建菜单子项(添加/删除商品) private JTable table;
private JTable table;//表格组件,用于展示商品数据 private DefaultTableModel tableModel;
private DefaultTableModel tableModel;//表格数据模型 private String selectedImagePath = null;
InventoryProductManagement() {
super("进货信息管理");//设置窗口标题 public InventoryProductManagement() {
menuBar = new JMenuBar();//实例化菜单栏 super("进货信息管理");
setJMenuBar(menuBar);//将菜单栏添加到窗体顶部 menuBar = new JMenuBar();
menu = new JMenu("菜单");//创建顶级菜单“菜单” setJMenuBar(menuBar);
menuBar.add(menu);//将菜单添加到菜单栏
//创建菜单项 menuItemAdd = new JMenuItem("进货");
menuItem1 = new JMenuItem("进货"); menuItemDelete = new JMenuItem("删除");
menuItem2 = new JMenuItem("删除"); menuBar.add(menuItemAdd);
menuItem3 = new JMenuItem("帮助"); menuBar.add(menuItemDelete);
//添加菜单项到菜单
menu.add(menuItem1); menuItemAdd.addActionListener(this);
menu.add(menuItem2); menuItemDelete.addActionListener(this);
menu.add(menuItem3);
// menu.add(menuItem3); setSize(600, 500);
//注册菜单项点击监听器this表示当前类处理事件 setLocationRelativeTo(null);
menuItem1.addActionListener(this);
menuItem2.addActionListener(this); // 表格初始化
menuItem3.addActionListener(this); String[] columnNames = {"商品照片","商品名称","商品类别","商品数量(件)","进货单价(元)"};
// menuItem3.addActionListener(this); tableModel = new DefaultTableModel(columnNames, 0) {
setSize(500,500);//设置窗口大小 @Override
setLocationRelativeTo(null);//窗口居中显示 public Class<?> getColumnClass(int column) {
// 表格初始化 if (column == 0) return Icon.class;
String[] columnNames = {"商品名称(种类)", "商品数量(件)", "进货单价(元)"};//定义表头,此处更改表头文字展示 return super.getColumnClass(column);
tableModel = new DefaultTableModel(columnNames, 0);//创建空表格模型 }
table = new JTable(tableModel);//基于模型创建表格
@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); JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER); add(scrollPane, BorderLayout.CENTER);
loadData(); // 初始化加载数据
// 初始化加载数据库数据 setVisible(true);
loadData();//加载数据库数据到表格
setVisible(true);//显示窗口
} }
// 加载数据库数据
private void loadData() { private void loadData() {
Jdbc jdbc = new Jdbc();//创建数据库连接对象 Jdbc jdbc = new Jdbc();
try { try {
//执行SQL查询获取商品名称/库存/进阶/售价/利润/销量) ResultSet rs = jdbc.query("SELECT name, type, count, purchase_price, image_path FROM commodity");
ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold FROM commodity"); tableModel.setRowCount(0); // 清空表格
// 清空旧数据
tableModel.setRowCount(0);//清空表格现有数据
// 填充新数据(遍历查询结果)
while (rs.next()) { while (rs.next()) {
//构建表格行数据(只显示名称/库存/进阶) String name = rs.getString("name");
Object[] row = { String type = rs.getString("type");
rs.getString("name"), int count = rs.getInt("count");
rs.getInt("count"), double price = rs.getDouble("purchase_price");
rs.getDouble("purchase_price"), String imagePath = rs.getString("image_path");
};
tableModel.addRow(row);//添加数据行到表格 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();//关闭结果集 rs.close();
jdbc.close();//关闭数据库连接 jdbc.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());//弹出错误提示 JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());
} }
} }
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem1) { if (e.getSource() == menuItemAdd) {
JFrame frame = new JFrame();//创建添加窗口 showAddProductWindow();
frame.setTitle("添加商品"); } else if (e.getSource() == menuItemDelete) {
frame.setLayout(new GridLayout(4, 2));//四行两列网格布局 showDeleteProductWindow();
//创建输入组件
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);
} }
} }
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<String> 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) { public static void main(String[] args) {
new InventoryProductManagement();//启动应用程序 SwingUtilities.invokeLater(InventoryProductManagement::new);
} }
} }

View File

@@ -1,127 +1,151 @@
package com.example; package com.example;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.io.File;
import java.awt.event.ActionListener;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
public class SalesProductManagement extends JFrame implements ActionListener { public class SalesProductManagement extends JFrame {
private JTable table; private JTable table;
private DefaultTableModel tableModel; private DefaultTableModel tableModel;
private JTextField idField, nameField, phoneField, addressField; private JTextField totalField;
private JButton addBtn; private JButton checkoutBtn;
private String userIdentity; // 当前用户身份
public SalesProductManagement() { public SalesProductManagement(String identity) {
this.userIdentity = identity;
setTitle("商品信息管理"); setTitle("商品销售信息管理");
setSize(800, 600); setSize(900, 600);
setLocationRelativeTo(null); setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout()); JPanel mainPanel = new JPanel(new BorderLayout());
// 创建表格面板 // 表格
JPanel tablePanel = new JPanel(new BorderLayout()); String[] columnNames = {"商品图片","名称","类别","单价","购买数量"};
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); tableModel = new DefaultTableModel(columnNames,0){
@Override
public boolean isCellEditable(int row, int column){
if(column == 3) return "admin".equals(userIdentity); // 单价列 admin 可编辑
return column == 4; // 购买数量列所有用户可编辑
}
// 创建表格模型 @Override
String[] columnNames = {"名称", "单价", "购买数量"}; public Class<?> getColumnClass(int column){
tableModel = new DefaultTableModel(columnNames, 0); 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 = new JTable(tableModel);
table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); table.setRowHeight(60);
table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
table.setRowHeight(25); // 图片渲染器
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); 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)); JPanel checkoutPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,10));
inputPanel.setBorder(BorderFactory.createTitledBorder("结算信息")); checkoutBtn = new JButton("结算");
inputPanel.setFont(new Font("微软雅黑", Font.PLAIN, 14)); totalField = new JTextField(10);
totalField.setEditable(false);
addBtn = new JButton("结算"); checkoutPanel.add(new JLabel("总金额:"));
addBtn.addActionListener(this); checkoutPanel.add(totalField);
checkoutPanel.add(checkoutBtn);
mainPanel.add(checkoutPanel, BorderLayout.SOUTH);
inputPanel.add(addBtn);
inputPanel.add(new JLabel("共计:"));
addressField = new JTextField();
inputPanel.add(addressField);
// 组装面板
mainPanel.add(tablePanel, BorderLayout.CENTER);
mainPanel.add(inputPanel, BorderLayout.SOUTH);
add(mainPanel); add(mainPanel);
loadData(); 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); setVisible(true);
} }
//主类,调试 private void loadData(){
public static void main(String[] args) {
new SalesProductManagement();
}
private void loadData() {
Jdbc jdbc = new Jdbc(); Jdbc jdbc = new Jdbc();
try { try{
ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold FROM commodity"); ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold,type,image_path FROM commodity");
// 清空旧数据
tableModel.setRowCount(0); tableModel.setRowCount(0);
// 填充新数据 while(rs.next()){
while (rs.next()) { String name = rs.getString("name");
Object[] row = { double price = rs.getDouble("selling_price");
rs.getString("name"), int quantity = rs.getInt("quantity_sold");
rs.getDouble("selling_price"), String type = rs.getString("type");
rs.getInt("quantity_sold"), 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); tableModel.addRow(row);
} }
rs.close(); rs.close();
jdbc.close(); jdbc.close();
} catch (SQLException e) { }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage()); JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage());
} }
} }
@Override private void calculateTotal(){
public void actionPerformed(ActionEvent e) { double total = 0.0;
if(e.getSource() == addBtn) { for(int i=0;i<tableModel.getRowCount();i++){
double total = 0.0; // 总金额 double price = Double.parseDouble(tableModel.getValueAt(i,3).toString());
int quantity = Integer.parseInt(tableModel.getValueAt(i,4).toString());
// 获取表格的行数 total += price*quantity;
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) + "");
} }
totalField.setText(String.format("%.2f 元",total));
} }
}
public static void main(String[] args){
new SalesProductManagement("admin"); // 测试 admin
}
}

View File

@@ -2,56 +2,76 @@ package com.example;
import javax.swing.*; import javax.swing.*;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.io.File;
import java.awt.event.ActionListener; 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.ResultSet;
import java.sql.SQLException;
public class StockProductManagement extends JFrame implements ActionListener { public class StockProductManagement extends JFrame implements java.awt.event.ActionListener {
JMenuBar menuBar; JMenuBar menuBar;
JMenu menu; JMenuItem menuItemAdd, menuItemDelete;
JMenuItem menuItem1,menuItem2,menuItem3;
private JTable table; private JTable table;
private DefaultTableModel tableModel; private DefaultTableModel tableModel;
StockProductManagement() { private String selectedImagePath = null;
public StockProductManagement() {
super("库存商品信息管理"); super("库存商品信息管理");
menuBar = new JMenuBar(); menuBar = new JMenuBar();
setJMenuBar(menuBar); setJMenuBar(menuBar);
menu = new JMenu("菜单");
menuBar.add(menu); menuItemAdd = new JMenuItem("添加商品");
menuItem1 = new JMenuItem("添加商品"); menuItemDelete = new JMenuItem("删除商品");
menuItem2 = new JMenuItem("删除商品"); menuBar.add(menuItemAdd);
menu.add(menuItem1); menuBar.add(menuItemDelete);
menu.add(menuItem2);
// menu.add(menuItem3); menuItemAdd.addActionListener(this);
menuItem1.addActionListener(this); menuItemDelete.addActionListener(this);
menuItem2.addActionListener(this);
// menuItem3.addActionListener(this); setSize(800, 500);
setSize(500,500);
setLocationRelativeTo(null); setLocationRelativeTo(null);
// 表头 // 表头增加“商品类别”列
String[] columnNames = {"商品名称", "商品数量", "进货单价", "销售单价", "单个利润","销售数量"}; String[] columnNames = {"商品照片","商品名称","商品类别","商品数量","进货单价","销售单价","单个利润","销售数量"};
tableModel = new DefaultTableModel(columnNames, 0){ tableModel = new DefaultTableModel(columnNames, 0){
@Override @Override
public boolean isCellEditable(int row, int column) { public boolean isCellEditable(int row, int column) {
return column == 5; return column == 7; // 只有销售数量可编辑
}
@Override
public Class<?> getColumnClass(int column) {
if(column == 0) return Icon.class; // 图片列
return super.getColumnClass(column);
} }
}; };
table = new JTable(tableModel); 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 -> { table.getModel().addTableModelListener(e -> {
int row = e.getFirstRow(); int row = e.getFirstRow();
int column = e.getColumn(); int column = e.getColumn();
if(column == 7) { // 销售数量列
if (column == 5) { // 销售数量列 String name = (String)tableModel.getValueAt(row, 1);
String name = (String) tableModel.getValueAt(row, 0); // 商品名称
Object value = tableModel.getValueAt(row, column); Object value = tableModel.getValueAt(row, column);
if(value != null && !value.toString().trim().isEmpty()) {
if (value != null && !value.toString().trim().isEmpty()) {
try { try {
int quantitySold = Integer.parseInt(value.toString().trim()); int quantitySold = Integer.parseInt(value.toString().trim());
Jdbc jdbc = new Jdbc(); Jdbc jdbc = new Jdbc();
@@ -64,143 +84,188 @@ public class StockProductManagement extends JFrame implements ActionListener {
} }
}); });
// 滚动面板
JScrollPane scrollPane = new JScrollPane(table); JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER); add(scrollPane, BorderLayout.CENTER);
// 初始化加载数据库数据
loadData(); loadData();
setVisible(true); setVisible(true);
} }
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() == menuItem1) { if(e.getSource() == menuItemAdd){
JFrame frame = new JFrame(); showAddProductWindow();
frame.setTitle("添加商品"); } else if(e.getSource() == menuItemDelete){
frame.setLayout(new GridLayout(5, 2)); deleteSelectedProduct();
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);
} }
} }
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<String> 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(); Jdbc jdbc = new Jdbc();
try { try{
ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold FROM commodity"); 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); tableModel.setRowCount(0);
// 填充新数据 while(rs.next()){
while (rs.next()) { String name = rs.getString("name");
Object[] row = { int count = rs.getInt("count");
rs.getString("name"), double purchasePrice = rs.getDouble("purchase_price");
rs.getInt("count"), double sellingPrice = rs.getDouble("selling_price");
rs.getDouble("purchase_price"), double profit = rs.getDouble("profit");
rs.getDouble("selling_price"), String quantitySold = rs.getString("quantity_sold");
rs.getDouble("profit"), 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); tableModel.addRow(row);
} }
rs.close(); rs.close();
jdbc.close(); jdbc.close();
} catch (SQLException e) { }catch(Exception e){
e.printStackTrace(); 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);
} }
} }

View File

@@ -85,7 +85,7 @@ public class UserManagement extends JFrame implements ActionListener {
// 添加用户 // 添加用户
if (e.getSource() == addItem) { if (e.getSource() == addItem) {
JFrame frame = new JFrame("添加用户"); JFrame frame = new JFrame("添加用户");
frame.setLayout(new GridLayout(5, 2)); frame.setLayout(new GridLayout(3, 2));
JLabel nameLabel = new JLabel("用户名:"); JLabel nameLabel = new JLabel("用户名:");
JTextField nameField = new JTextField(); JTextField nameField = new JTextField();
JLabel passLabel = new JLabel("密码:"); JLabel passLabel = new JLabel("密码:");
@@ -150,29 +150,26 @@ public class UserManagement extends JFrame implements ActionListener {
String oldUsername = (String) tableModel.getValueAt(row, 0); String oldUsername = (String) tableModel.getValueAt(row, 0);
JFrame frame = new JFrame("修改用户"); 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 nameField = new JTextField((String) tableModel.getValueAt(row, 0));
JTextField passField = new JTextField((String) tableModel.getValueAt(row, 1)); JTextField passField = new JTextField((String) tableModel.getValueAt(row, 1));
JTextField emailField = new JTextField((String) tableModel.getValueAt(row, 2)); JTextField identityField = new JTextField((String) tableModel.getValueAt(row, 2));
JTextField phoneField = new JTextField((String) tableModel.getValueAt(row, 3));
JButton saveButton = new JButton("保存"); JButton saveButton = new JButton("保存");
JButton cancelButton = new JButton("取消"); JButton cancelButton = new JButton("取消");
frame.add(new JLabel("用户名:")); frame.add(nameField); frame.add(new JLabel("用户名:")); frame.add(nameField);
frame.add(new JLabel("密码:")); frame.add(passField); frame.add(new JLabel("密码:")); frame.add(passField);
frame.add(new JLabel("邮箱:")); frame.add(emailField); frame.add(new JLabel("身份:")); frame.add(identityField);
frame.add(new JLabel("电话:")); frame.add(phoneField);
frame.add(saveButton); frame.add(cancelButton); frame.add(saveButton); frame.add(cancelButton);
saveButton.addActionListener(ev -> { saveButton.addActionListener(ev -> {
String username = nameField.getText(); String username = nameField.getText();
String password = passField.getText(); String password = passField.getText();
String email = emailField.getText(); String identity = identityField.getText();
String phone = phoneField.getText();
Jdbc jdbc = new Jdbc(); Jdbc jdbc = new Jdbc();
try { 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(); jdbc.close();
loadData(); loadData();
frame.dispose(); frame.dispose();