Compare commits

...

10 Commits

Author SHA1 Message Date
lu
a3f85588c6 完整版 2025-10-07 14:13:18 +08:00
lu
d98573b777 库存列表筛选功能 2025-09-25 17:08:07 +08:00
lx
f9d1241a2d 完整版本 2025-09-24 23:13:03 +08:00
lu
2f386d22a6 列表显示图片,添加时添加图片,物品分类别 2025-09-24 20:33:06 +08:00
lcm
12b7b88198 Merge pull request '分用户登录' (#5) from lcm into master
Reviewed-on: #5
2025-09-24 10:11:58 +00:00
lu
7f954cfeff 分用户登录 2025-09-24 13:18:41 +08:00
lx
5106616b8f Merge remote-tracking branch 'origin/master' 2025-09-23 17:40:20 +08:00
lx
5339a4c0ee 一次测试 2025-09-23 17:38:56 +08:00
lcm
4e0a460a59 Merge pull request '111' (#4) from fgl into master
Reviewed-on: #4
2025-09-19 06:35:48 +00:00
fgl
76a7f5df6d 111 2025-09-19 14:33:37 +08:00
11 changed files with 853 additions and 384 deletions

BIN
images/a.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 649 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: 35 KiB

View File

@@ -1,31 +1,67 @@
package com.example; package com.example;
import javax.swing.*; import javax.swing.*;
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.sql.ResultSet;
import java.sql.SQLException;
public class Home extends JFrame implements ActionListener { public class Home extends JFrame implements ActionListener {
JMenuBar menuBar; JMenuBar menuBar;
JMenu menu;
// 库存菜单 进货菜单 销售菜单 // 库存菜单 进货菜单 销售菜单
JMenuItem StockMenuItem,InventoryMenuItem,SalesMenuItem; JButton StockMenu,InventoryMenu,SalesMenu,UserMenu,LogoutMenu;
private String userIdentity;
class BackgroundPanel extends JPanel {
private Image bg;
public BackgroundPanel(String path) {
bg = new ImageIcon(path).getImage();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}
}
Home() { Home(String username) {
super("超市进销存信息管理系统"); super("超市进销存信息管理系统");
BackgroundPanel bgPanel = new BackgroundPanel("images\\a.jpg");
bgPanel.setLayout(new BorderLayout());
setContentPane(bgPanel);
menuBar = new JMenuBar(); menuBar = new JMenuBar();
menu = new JMenu("菜单"); StockMenu = new JButton("库存信息管理");
StockMenuItem = new JMenuItem("库存信息管理"); InventoryMenu = new JButton("进货信息管理");
InventoryMenuItem = new JMenuItem("进货信息管理"); SalesMenu = new JButton("销售信息管理");
SalesMenuItem = new JMenuItem("销售信息管理"); LogoutMenu = new JButton("退出登录");
menu.add(StockMenuItem); menuBar.add(StockMenu);
menu.add(InventoryMenuItem); menuBar.add(InventoryMenu);
menu.add(SalesMenuItem); menuBar.add(SalesMenu);
menuBar.add(menu); menuBar.add(LogoutMenu);
setJMenuBar(menuBar); setJMenuBar(menuBar);
StockMenuItem.addActionListener(this); StockMenu.addActionListener(this);
InventoryMenuItem.addActionListener(this); InventoryMenu.addActionListener(this);
SalesMenuItem.addActionListener(this); SalesMenu.addActionListener(this);
LogoutMenu.addActionListener(this);
Jdbc jdbc = new Jdbc();
String sql = "select * from user where username='"+username+"'";
try {
ResultSet rs = jdbc.query(sql);
if(rs.next()){
userIdentity = rs.getString("identity");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
if(userIdentity.equals("admin")){
UserMenu = new JButton("用户管理");
menuBar.add(UserMenu);
UserMenu.addActionListener(this);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500); setSize(500,500);
setLocationRelativeTo(null); setLocationRelativeTo(null);
@@ -33,14 +69,24 @@ public class Home extends JFrame implements ActionListener {
} }
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if(e.getSource()==StockMenuItem){ if(e.getSource()==StockMenu){
new StockProductManagement(); new StockProductManagement();
} }
if(e.getSource()==InventoryMenuItem){ if(e.getSource()==InventoryMenu){
new InventoryProductManagement(); new InventoryProductManagement();
} }
if(e.getSource()==SalesMenuItem){ if(e.getSource()==SalesMenu){
new SalesProductManagement(); new SalesProductManagement(userIdentity);
}
if(e.getSource()==UserMenu){
new UserManagement();
}
if(e.getSource()==LogoutMenu){
new Main();
this.dispose();
} }
} }
public static void main(String[] args) {
new Home("admin");
}
} }

View File

@@ -2,61 +2,100 @@ 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;
InventoryProductManagement() { private String selectedImagePath = null;
public InventoryProductManagement() {
super("进货信息管理"); super("进货信息管理");
menuBar = new JMenuBar(); menuBar = new JMenuBar();
setJMenuBar(menuBar); setJMenuBar(menuBar);
menu = new JMenu("菜单");
menuBar.add(menu);
menuItem1 = new JMenuItem("添加商品");
menuItem2 = new JMenuItem("删除商品");
menu.add(menuItem1);
menu.add(menuItem2);
// menu.add(menuItem3);
menuItem1.addActionListener(this);
menuItem2.addActionListener(this);
// menuItem3.addActionListener(this);
setSize(500,500);
setLocationRelativeTo(null);
// 表头
String[] columnNames = {"商品名称", "商品数量", "进货单价"};
tableModel = new DefaultTableModel(columnNames, 0);
table = new JTable(tableModel);
// 滚动面板 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); JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER); add(scrollPane, BorderLayout.CENTER);
loadData(); // 初始化加载数据
// 初始化加载数据库数据
loadData();
setVisible(true); setVisible(true);
} }
// 加载数据库数据
private void loadData() { private void loadData() {
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 name, type, count, purchase_price, image_path FROM commodity");
// 清空旧数据 tableModel.setRowCount(0); // 清空表格
tableModel.setRowCount(0);
// 填充新数据
while (rs.next()) { while (rs.next()) {
Object[] row = { String name = rs.getString("name");
rs.getString("name"), String type = rs.getString("type");
rs.getInt("count"), int count = rs.getInt("count");
rs.getDouble("purchase_price"), 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); tableModel.addRow(row);
} }
rs.close(); rs.close();
@@ -69,101 +108,156 @@ public class InventoryProductManagement extends JFrame implements ActionListener
@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();
}
}
private void showAddProductWindow() {
JFrame frame = new JFrame("添加商品");
frame.setLayout(new GridLayout(6,2));
JLabel nameLabel = new JLabel("商品名称:"); JLabel nameLabel = new JLabel("商品名称:");
JTextField nameField = new JTextField(); JTextField nameField = new JTextField();
JLabel countLabel = new JLabel("商品数量:"); JLabel countLabel = new JLabel("商品数量:");
JTextField countField = new JTextField(); JTextField countField = new JTextField();
JLabel purchasePriceLabel = new JLabel("进货单价:"); JLabel purchasePriceLabel = new JLabel("进货单价:");
JTextField purchasePriceField = new JTextField(); 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 addButton = new JButton("添加");
JButton cancelButton = new JButton("取消"); JButton cancelButton = new JButton("取消");
frame.add(nameLabel);
frame.add(nameField); frame.add(nameLabel); frame.add(nameField);
frame.add(countLabel); frame.add(countLabel); frame.add(countField);
frame.add(countField); frame.add(purchasePriceLabel); frame.add(purchasePriceField);
frame.add(purchasePriceLabel); frame.add(typeLabel); frame.add(typeComboBox);
frame.add(purchasePriceField); frame.add(imageLabel); frame.add(chooseImageButton);
frame.add(addButton); frame.add(addButton); frame.add(cancelButton);
frame.add(cancelButton);
addButton.addActionListener(new ActionListener() { // 图片选择事件
@Override chooseImageButton.addActionListener(ev -> {
public void actionPerformed(ActionEvent e) { 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(); String name = nameField.getText();
int count = Integer.parseInt(countField.getText()); int count;
double purchasePrice = Double.parseDouble(purchasePriceField.getText()); 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(); Jdbc jdbc = new Jdbc();
try { try {
jdbc.update("INSERT INTO commodity (name, count, purchase_price, quantity_sold) VALUES ('" + name + "', " + count + ", " + purchasePrice + ", " + 0 + ");"); 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(); jdbc.close();
// 刷新数据
loadData(); loadData();
// 关闭弹窗
frame.dispose(); frame.dispose();
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"添加商品失败: "+ex.getMessage()); JOptionPane.showMessageDialog(frame,"添加商品失败: "+ex.getMessage());
} }
}
}); });
cancelButton.addActionListener(new ActionListener() {
@Override cancelButton.addActionListener(ev -> frame.dispose());
public void actionPerformed(ActionEvent e) {
frame.dispose(); frame.setSize(400, 300);
}
});
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true); frame.setVisible(true);
} }
else if (e.getSource() == menuItem2) {
JFrame frame = new JFrame(); private void showDeleteProductWindow() {
frame.setTitle("删除商品"); JFrame frame = new JFrame("删除商品");
frame.setLayout(new GridLayout(2,2)); frame.setLayout(new GridLayout(2,2));
JLabel nameLabel = new JLabel("商品名称:"); JLabel nameLabel = new JLabel("商品名称:");
JTextField nameField = new JTextField(); JTextField nameField = new JTextField();
JButton deleteButton = new JButton("删除"); JButton deleteButton = new JButton("删除");
JButton cancelButton = new JButton("取消"); JButton cancelButton = new JButton("取消");
frame.add(nameLabel); frame.add(nameLabel); frame.add(nameField);
frame.add(nameField); frame.add(deleteButton); frame.add(cancelButton);
frame.add(deleteButton);
frame.add(cancelButton); deleteButton.addActionListener(ev -> {
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText(); String name = nameField.getText();
// 调用数据库删除方法
Jdbc jdbc = new Jdbc(); Jdbc jdbc = new Jdbc();
try { 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.update("DELETE FROM commodity WHERE name='"+name+"'");
jdbc.close(); jdbc.close();
// 刷新数据
// 删除图片文件
if(imagePath != null && !imagePath.isEmpty()) {
File imgFile = new File("images/"+imagePath);
if(imgFile.exists()) imgFile.delete();
}
loadData(); loadData();
// 关闭弹窗
frame.dispose(); frame.dispose();
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "删除商品失败: "+ex.getMessage()); JOptionPane.showMessageDialog(frame, "删除商品失败: "+ex.getMessage());
} }
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
}); });
cancelButton.addActionListener(ev -> frame.dispose());
frame.setSize(300,200); frame.setSize(300,200);
frame.setLocationRelativeTo(null); frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true); frame.setVisible(true);
} }
}
public static void main(String[] args) { public static void main(String[] args) {
new InventoryProductManagement(); new InventoryProductManagement();
} }

View File

@@ -46,7 +46,6 @@ public class Main extends JFrame implements ActionListener {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb1){ if(e.getSource()==jb1){
Jdbc jdbc = new Jdbc(); Jdbc jdbc = new Jdbc();
String sql = "select * from user where username='"+tf1.getText()+"' and password='"+tf2.getText()+"'"; ; String sql = "select * from user where username='"+tf1.getText()+"' and password='"+tf2.getText()+"'"; ;
@@ -54,7 +53,7 @@ public class Main extends JFrame implements ActionListener {
ResultSet rs = jdbc.query(sql); ResultSet rs = jdbc.query(sql);
if(rs.next()&&tf3.getText().equals(jb3.getText())) { if(rs.next()&&tf3.getText().equals(jb3.getText())) {
JOptionPane.showMessageDialog(null, "登录成功"); JOptionPane.showMessageDialog(null, "登录成功");
new Home(); new Home(rs.getString("username"));
this.setVisible(false); this.setVisible(false);
} }
else{ else{

View File

@@ -1,104 +1,267 @@
package com.example; package com.example;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.TableModelEvent;
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;
public class SalesProductManagement extends JFrame implements ActionListener { public class SalesProductManagement extends JFrame {
JButton btn1; private JTable table;
JLabel lab1,lab2,lab3,lab4,lab5,lab6,lab7; private DefaultTableModel tableModel;
JTextField text2,text3,text5,text6,text8,text9,text10; private JTextField totalField;
// JPasswordField passwordfile; private JButton checkoutBtn;
JPanel panel1,panel2,panel3; private JButton addBtn; // 新增:上架按钮
private JButton removeBtn; // 新增:下架按钮
private String userIdentity; // 当前用户身份
public SalesProductManagement(String identity) {
this.userIdentity = identity;
setTitle("商品销售信息管理");
SalesProductManagement(){ setSize(900, 600);
super("销售信息管理");
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
lab1=new JLabel("名称",JLabel.CENTER);
lab2=new JLabel("单价",JLabel.CENTER);
lab3=new JLabel("数量",JLabel.CENTER);
lab4=new JLabel("总计:",JLabel.CENTER);
lab5=new JLabel("苹果",JLabel.CENTER);
lab6=new JLabel("香蕉",JLabel.CENTER);
lab7=new JLabel("橘子",JLabel.CENTER);
text2=new JTextField("2"+"",JTextField.CENTER);
text3=new JTextField(3);
text5=new JTextField("3"+"",JTextField.CENTER);
text6=new JTextField(3);
text8=new JTextField("5"+"",JTextField.CENTER);
text9=new JTextField(3);
text10=new JTextField(5);
btn1=new JButton("结算");
btn1.addActionListener(this);
add(panel1);
panel1.setLayout(new GridLayout(1,3,5,5));
panel1.add(lab1);
panel1.add(lab2);
panel1.add(lab3);
panel1.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40));
add(panel2);
panel2.setLayout(new GridLayout(3,3,5,5));
panel2.add(lab5);
panel2.add(text2);
panel2.add(text3);
panel2.add(lab6);
panel2.add(text5);
panel2.add(text6);
panel2.add(lab7);
panel2.add(text8);
panel2.add(text9);
panel2.setMaximumSize(new Dimension(Integer.MAX_VALUE, 120));
add(panel3);
panel3.setLayout(new GridLayout(1,3,5,5));
panel3.add(btn1);
panel3.add(lab4);
panel3.add(text10);
panel3.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40));
setLayout(new GridLayout(3,1));
setSize(500,500);
setLocationRelativeTo(null); setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel(new BorderLayout());
// 顶部按钮面板
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
addBtn = new JButton("上架商品");
removeBtn = new JButton("从界面下架");
// 只有管理员可以上架商品
addBtn.setEnabled("admin".equals(userIdentity));
topPanel.add(addBtn);
topPanel.add(removeBtn);
mainPanel.add(topPanel, BorderLayout.NORTH);
// 表格
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; // 购买数量列所有用户可编辑
}
@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.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);
mainPanel.add(scrollPane, BorderLayout.CENTER);
// 结算面板
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();
setupEventListeners(); // 统一管理事件监听器
setVisible(true); setVisible(true);
} }
@Override
public void actionPerformed(ActionEvent e) { // 设置事件监听器
// 判断事件源是否为结算按钮 private void setupEventListeners() {
if (e.getSource() == btn1) { // 结算按钮事件
checkoutBtn.addActionListener(e -> calculateTotal());
// 上架按钮事件
addBtn.addActionListener(e -> addProductFromDatabase());
// 下架按钮事件
removeBtn.addActionListener(e -> removeSelectedProducts());
// 表格模型监听器,处理数据更新
tableModel.addTableModelListener(e -> {
if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int col = e.getColumn();
String name = tableModel.getValueAt(row, 1).toString(); // 商品名称
try { try {
// 获取单价(从文本框提取数字部分) Jdbc jdbc = new Jdbc();
double applePrice = Double.parseDouble(text2.getText().replace("", "")); if (col == 3 && "admin".equals(userIdentity)) { // 单价
double bananaPrice = Double.parseDouble(text5.getText().replace("", "")); double price = Double.parseDouble(tableModel.getValueAt(row, 3).toString());
double orangePrice = Double.parseDouble(text8.getText().replace("", "")); jdbc.update("UPDATE commodity SET selling_price=" + price + " WHERE name='" + name + "'");
} else if (col == 4) { // 购买数量
// 获取数量(处理空输入情况) int quantity = Integer.parseInt(tableModel.getValueAt(row, 4).toString());
int appleCount = text3.getText().trim().isEmpty() ? 0 : Integer.parseInt(text3.getText().trim()); jdbc.update("UPDATE commodity SET quantity_sold=" + quantity + " WHERE name='" + name + "'");
int bananaCount = text6.getText().trim().isEmpty() ? 0 : Integer.parseInt(text6.getText().trim()); }
int orangeCount = text9.getText().trim().isEmpty() ? 0 : Integer.parseInt(text9.getText().trim()); jdbc.close();
} catch (Exception ex) {
// 计算总金额 ex.printStackTrace();
double total = (applePrice * appleCount) + (bananaPrice * bananaCount) + (orangePrice * orangeCount); JOptionPane.showMessageDialog(this, "更新数据库失败: " + ex.getMessage());
// 显示结果,保留两位小数
text10.setText(String.format("%.2f元", total));
} catch (NumberFormatException ex) {
// 处理输入非数字的情况
JOptionPane.showMessageDialog(this, "请输入有效的数字", "输入错误", JOptionPane.ERROR_MESSAGE);
} }
} }
});
} }
// 从数据库上架商品(选择数据库中未显示的商品添加到界面)
private void addProductFromDatabase() {
try {
Jdbc jdbc = new Jdbc();
// 查询数据库中所有商品
ResultSet rs = jdbc.query("SELECT name, selling_price, quantity_sold, type, image_path FROM commodity");
// 收集已在界面上的商品名称
DefaultListModel<String> availableProducts = new DefaultListModel<>();
while (rs.next()) {
String name = rs.getString("name");
boolean isInTable = false;
// 检查商品是否已在表格中
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (tableModel.getValueAt(i, 1).toString().equals(name)) {
isInTable = true;
break;
}
}
if (!isInTable) {
availableProducts.addElement(name);
}
}
rs.close();
if (availableProducts.size() == 0) {
JOptionPane.showMessageDialog(this, "所有商品已上架!");
jdbc.close();
return;
}
// 显示可选商品列表供选择
JList<String> productList = new JList<>(availableProducts);
productList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
int result = JOptionPane.showConfirmDialog(
this,
new JScrollPane(productList),
"选择要上架的商品",
JOptionPane.OK_CANCEL_OPTION
);
if (result == JOptionPane.OK_OPTION) {
// 上架选中的商品
for (String selectedName : productList.getSelectedValuesList()) {
ResultSet productRs = jdbc.query(
"SELECT name, selling_price, quantity_sold, type, image_path FROM commodity WHERE name='" + selectedName + "'"
);
if (productRs.next()) {
String name = productRs.getString("name");
double price = productRs.getDouble("selling_price");
int quantity = productRs.getInt("quantity_sold");
String type = productRs.getString("type");
String imagePath = productRs.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);
}
productRs.close();
}
JOptionPane.showMessageDialog(this, "已成功上架选中商品!");
}
jdbc.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "上架商品失败: " + e.getMessage());
}
}
// 从界面下架商品(仅从当前界面移除,不删除数据库记录)
private void removeSelectedProducts() {
int[] selectedRows = table.getSelectedRows();
if (selectedRows.length == 0) {
JOptionPane.showMessageDialog(this, "请先选择要下架的商品!");
return;
}
// 从后往前删除,避免索引混乱
for (int i = selectedRows.length - 1; i >= 0; i--) {
tableModel.removeRow(selectedRows[i]);
}
JOptionPane.showMessageDialog(this, "已成功下架 " + selectedRows.length + " 件商品!");
calculateTotal(); // 更新总金额
}
private void loadData() {
Jdbc jdbc = new Jdbc();
try {
ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold,type,image_path FROM commodity");
tableModel.setRowCount(0);
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 (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());
}
}
private void calculateTotal() {
double total = 0.0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
double price = Double.parseDouble(tableModel.getValueAt(i, 3).toString());
int quantity = Integer.parseInt(tableModel.getValueAt(i, 4).toString());
total += price * quantity;
}
totalField.setText(String.format("%.2f 元", total));
}
public static void main(String[] args) { public static void main(String[] args) {
new SalesProductManagement(); new SalesProductManagement("admin"); // 测试 admin
} }
} }

View File

@@ -2,55 +2,81 @@ 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.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.util.HashSet;
import java.util.Set;
public class StockProductManagement extends JFrame implements ActionListener { public class StockProductManagement extends JFrame {
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem1,menuItem2,menuItem3;
private JTable table; private JTable table;
private DefaultTableModel tableModel; private DefaultTableModel tableModel;
StockProductManagement() { private JTextField searchField;
private JComboBox<String> categoryComboBox;
private JButton resetButton;
public StockProductManagement() {
super("库存商品信息管理"); super("库存商品信息管理");
menuBar = new JMenuBar();
setJMenuBar(menuBar); setSize(900, 550);
menu = new JMenu("菜单");
menuBar.add(menu);
menuItem1 = new JMenuItem("添加商品");
menuItem2 = new JMenuItem("删除商品");
menu.add(menuItem1);
menu.add(menuItem2);
// menu.add(menuItem3);
menuItem1.addActionListener(this);
menuItem2.addActionListener(this);
// menuItem3.addActionListener(this);
setSize(500,500);
setLocationRelativeTo(null); setLocationRelativeTo(null);
// 表头 //顶部工具面板
String[] columnNames = {"商品名称", "商品数量", "进货单价", "销售单价", "单个利润","销售数量"}; JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
topPanel.add(new JLabel("搜索商品名称:"));
searchField = new JTextField(15);
topPanel.add(searchField);
JButton searchButton = new JButton("搜索");
topPanel.add(searchButton);
topPanel.add(new JLabel("筛选类别:"));
categoryComboBox = new JComboBox<>();
categoryComboBox.addItem("全部");
topPanel.add(categoryComboBox);
resetButton = new JButton("重置");
topPanel.add(resetButton);
add(topPanel, BorderLayout.NORTH);
// 表格
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());
@@ -64,142 +90,87 @@ 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(); searchButton.addActionListener(ev -> reloadData());
categoryComboBox.addActionListener(ev -> reloadData());
resetButton.addActionListener(ev -> { // 重置功能
searchField.setText("");
categoryComboBox.setSelectedItem("全部");
reloadData();
});
reloadData(); // 初次加载
setVisible(true); setVisible(true);
} }
@Override
public void actionPerformed(ActionEvent e) { /**
if (e.getSource() == menuItem1) { * 按条件加载数据
JFrame frame = new JFrame(); */
frame.setTitle("添加商品"); private void reloadData(){
frame.setLayout(new GridLayout(5, 2)); String keyword = searchField.getText().trim();
JLabel nameLabel = new JLabel("商品名称:"); String category = (String) categoryComboBox.getSelectedItem();
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(); Jdbc jdbc = new Jdbc();
try{ try{
jdbc.update("INSERT INTO commodity (name, count, purchase_price, selling_price, profit) VALUES ('" + name + "', " + count + ", " + purchasePrice + ", " + sellingPrice + ", " + (sellingPrice - purchasePrice) + ", 0);"); StringBuilder sql = new StringBuilder("SELECT name,count,purchase_price,selling_price,profit,quantity_sold,type,image_path FROM commodity WHERE 1=1 ");
jdbc.close(); if(!keyword.isEmpty()){
// 刷新数据 sql.append("AND name LIKE '%").append(keyword).append("%' ");
loadData();
// 关闭弹窗
frame.dispose();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "添加商品失败: " + ex.getMessage());
} }
if(category != null && !"全部".equals(category)){
sql.append("AND type='").append(category).append("' ");
} }
});
cancelButton.addActionListener(new ActionListener() { ResultSet rs = jdbc.query(sql.toString());
@Override tableModel.setRowCount(0);
public void actionPerformed(ActionEvent e) { Set<String> categories = new HashSet<>();
frame.dispose();
} while(rs.next()){
}); String name = rs.getString("name");
frame.setSize(300, 200); int count = rs.getInt("count");
setLocationRelativeTo(null); double purchasePrice = rs.getDouble("purchase_price");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); double sellingPrice = rs.getDouble("selling_price");
frame.setVisible(true); double profit = rs.getDouble("profit");
} String quantitySold = rs.getString("quantity_sold");
else if (e.getSource() == menuItem2) { String type = rs.getString("type");
JFrame frame = new JFrame(); String imagePath = rs.getString("image_path");
frame.setTitle("删除商品");
frame.setLayout(new GridLayout(2, 2)); categories.add(type);
JLabel nameLabel = new JLabel("商品名称:");
JTextField nameField = new JTextField(); ImageIcon icon = null;
JButton deleteButton = new JButton("删除"); if(imagePath!=null && !imagePath.isEmpty()){
JButton cancelButton = new JButton("取消"); File imgFile = new File("images/"+imagePath);
frame.add(nameLabel); if(imgFile.exists()){
frame.add(nameField); icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath())
frame.add(deleteButton); .getImage().getScaledInstance(50,50,Image.SCALE_SMOOTH));
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() { Object[] row = {icon,name,type,count,purchasePrice,sellingPrice,profit,quantitySold};
Jdbc jdbc = new Jdbc();
try {
ResultSet rs = jdbc.query("SELECT name,count,purchase_price,selling_price,profit,quantity_sold 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"),
};
tableModel.addRow(row); tableModel.addRow(row);
} }
rs.close(); rs.close();
jdbc.close(); jdbc.close();
} catch (SQLException e) {
// 更新类别下拉框
String selected = (String) categoryComboBox.getSelectedItem();
categoryComboBox.removeAllItems();
categoryComboBox.addItem("全部");
for(String c : categories){
categoryComboBox.addItem(c);
}
if(selected != null && !selected.isEmpty()){
categoryComboBox.setSelectedItem(selected);
}
}catch(Exception e){
e.printStackTrace(); e.printStackTrace();
JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage()); JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage());
} }
} }
public static void main(String[] args){ public static void main(String[] args){
new StockProductManagement(); new StockProductManagement();
} }

View File

@@ -0,0 +1,196 @@
package com.example;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserManagement extends JFrame implements ActionListener {
JMenuBar menuBar;
JMenuItem addItem, deleteItem, updateItem, refreshItem;
private JTable table;
private DefaultTableModel tableModel;
public UserManagement() {
super("用户信息管理");
// 菜单栏
menuBar = new JMenuBar();
setJMenuBar(menuBar);
addItem = new JMenuItem("添加用户");
deleteItem = new JMenuItem("删除用户");
updateItem = new JMenuItem("修改用户");
refreshItem = new JMenuItem("刷新数据");
menuBar.add(addItem);
menuBar.add(deleteItem);
menuBar.add(updateItem);
menuBar.add(refreshItem);
addItem.addActionListener(this);
deleteItem.addActionListener(this);
updateItem.addActionListener(this);
refreshItem.addActionListener(this);
// 表格模型
String[] columnNames = {"用户名", "密码", "身份"};
tableModel = new DefaultTableModel(columnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false; // 不直接在表格里改
}
};
table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
setSize(600, 400);
setLocationRelativeTo(null);
// 初始加载
loadData();
setVisible(true);
}
// 加载 identity=user 的数据
private void loadData() {
Jdbc jdbc = new Jdbc();
try {
ResultSet rs = jdbc.query("SELECT username,password,identity FROM user WHERE identity='user'");
tableModel.setRowCount(0);
while (rs.next()) {
Object[] row = {
rs.getString("username"),
rs.getString("password"),
rs.getString("identity")
};
tableModel.addRow(row);
}
rs.close();
jdbc.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());
}
}
@Override
public void actionPerformed(ActionEvent e) {
// 添加用户
if (e.getSource() == addItem) {
JFrame frame = new JFrame("添加用户");
frame.setLayout(new GridLayout(3, 2));
JLabel nameLabel = new JLabel("用户名:");
JTextField nameField = new JTextField();
JLabel passLabel = new JLabel("密码:");
JPasswordField passField = new JPasswordField();
JButton addButton = new JButton("添加");
JButton cancelButton = new JButton("取消");
frame.add(nameLabel); frame.add(nameField);
frame.add(passLabel); frame.add(passField);
frame.add(addButton); frame.add(cancelButton);
addButton.addActionListener(ev -> {
String username = nameField.getText();
String password = passField.getText();
Jdbc jdbc = new Jdbc();
try {
jdbc.update("INSERT INTO user (username,password,identity) VALUES ('"
+ username + "','" + password + "','user')");
jdbc.close();
loadData();
frame.dispose();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "添加失败: " + ex.getMessage());
}
});
cancelButton.addActionListener(ev -> frame.dispose());
frame.setSize(400, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// 删除用户
else if (e.getSource() == deleteItem) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(this, "请先选择要删除的用户!");
return;
}
String username = (String) tableModel.getValueAt(row, 0);
int confirm = JOptionPane.showConfirmDialog(this, "确定删除用户: " + username + " ?", "确认", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
Jdbc jdbc = new Jdbc();
try {
jdbc.update("DELETE FROM user WHERE username='" + username + "'");
jdbc.close();
loadData();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "删除失败: " + ex.getMessage());
}
}
}
// 修改用户
else if (e.getSource() == updateItem) {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(this, "请先选择要修改的用户!");
return;
}
String oldUsername = (String) tableModel.getValueAt(row, 0);
JFrame frame = new JFrame("修改用户");
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 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(identityField);
frame.add(saveButton); frame.add(cancelButton);
saveButton.addActionListener(ev -> {
String username = nameField.getText();
String password = passField.getText();
String identity = identityField.getText();
Jdbc jdbc = new Jdbc();
try {
jdbc.update("UPDATE user SET username='" + username + "', password='" + password + "', identity='" + identity + "' WHERE username='" + oldUsername + "'");
jdbc.close();
loadData();
frame.dispose();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "修改失败: " + ex.getMessage());
}
});
cancelButton.addActionListener(ev -> frame.dispose());
frame.setSize(400, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// 刷新数据
else if (e.getSource() == refreshItem) {
loadData();
}
}
public static void main(String[] args) {
new UserManagement();
}
}