完整版本

This commit is contained in:
lx
2025-09-24 23:13:03 +08:00
parent 2f386d22a6
commit f9d1241a2d
3 changed files with 178 additions and 57 deletions

View File

@@ -29,7 +29,7 @@ public class Home extends JFrame implements ActionListener {
Home(String username) { Home(String username) {
super("超市进销存信息管理系统"); super("超市进销存信息管理系统");
BackgroundPanel bgPanel = new BackgroundPanel("E:\\SuManagement\\images\\a.jpg"); BackgroundPanel bgPanel = new BackgroundPanel("images\\a.jpg");
bgPanel.setLayout(new BorderLayout()); bgPanel.setLayout(new BorderLayout());
setContentPane(bgPanel); setContentPane(bgPanel);
@@ -52,7 +52,7 @@ public class Home extends JFrame implements ActionListener {
userIdentity = rs.getString("identity"); userIdentity = rs.getString("identity");
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if(userIdentity.equals("admin")){ if(userIdentity.equals("admin")){
UserMenu = new JButton("用户管理"); UserMenu = new JButton("用户管理");

View File

@@ -54,7 +54,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(rs.getString("username")); new Home(rs.getString("username"));
this.setVisible(false); this.setVisible(false);
} }
else{ else{

View File

@@ -6,6 +6,7 @@ import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer; import javax.swing.table.TableCellRenderer;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File; import java.io.File;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -15,7 +16,9 @@ public class SalesProductManagement extends JFrame {
private DefaultTableModel tableModel; private DefaultTableModel tableModel;
private JTextField totalField; private JTextField totalField;
private JButton checkoutBtn; private JButton checkoutBtn;
private String userIdentity; // 当前用户身份 private JButton addBtn; // 新增:上架按钮
private JButton removeBtn; // 新增:下架按钮
private String userIdentity; // 当前用户身份
public SalesProductManagement(String identity) { public SalesProductManagement(String identity) {
this.userIdentity = identity; this.userIdentity = identity;
@@ -27,20 +30,30 @@ public class SalesProductManagement extends JFrame {
JPanel mainPanel = new JPanel(new BorderLayout()); 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 = {"商品图片","名称","类别","单价","购买数量"}; 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) {
if(column == 3) return "admin".equals(userIdentity); // 单价列 admin 可编辑 if (column == 3) return "admin".equals(userIdentity); // 单价列 admin 可编辑
return column == 4; // 购买数量列所有用户可编辑 return column == 4; // 购买数量列所有用户可编辑
} }
@Override @Override
public Class<?> getColumnClass(int column){ public Class<?> getColumnClass(int column) {
if(column==0) return Icon.class; if (column == 0) return Icon.class;
if(column==3) return Double.class; if (column == 3) return Double.class;
if(column==4) return Integer.class; if (column == 4) return Integer.class;
return String.class; return String.class;
} }
}; };
@@ -50,10 +63,11 @@ public class SalesProductManagement extends JFrame {
// 图片渲染器 // 图片渲染器
table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() { table.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
JLabel label = new JLabel(); JLabel label = new JLabel();
@Override @Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
label.setHorizontalAlignment(JLabel.CENTER); label.setHorizontalAlignment(JLabel.CENTER);
label.setIcon((Icon)value); label.setIcon((Icon) value);
return label; return label;
} }
}); });
@@ -62,7 +76,7 @@ public class SalesProductManagement extends JFrame {
mainPanel.add(scrollPane, BorderLayout.CENTER); mainPanel.add(scrollPane, BorderLayout.CENTER);
// 结算面板 // 结算面板
JPanel checkoutPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,10)); JPanel checkoutPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
checkoutBtn = new JButton("结算"); checkoutBtn = new JButton("结算");
totalField = new JTextField(10); totalField = new JTextField(10);
totalField.setEditable(false); totalField.setEditable(false);
@@ -74,41 +88,148 @@ public class SalesProductManagement extends JFrame {
add(mainPanel); add(mainPanel);
loadData(); loadData();
setupEventListeners(); // 统一管理事件监听器
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(){ // 新增:统一设置事件监听器
private void setupEventListeners() {
// 结算按钮事件
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 {
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());
}
}
});
}
// 新增:从数据库上架商品(选择数据库中未显示的商品添加到界面)
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(); Jdbc jdbc = new Jdbc();
try{ try {
ResultSet rs = jdbc.query("SELECT name,selling_price,quantity_sold,type,image_path 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"); String name = rs.getString("name");
double price = rs.getDouble("selling_price"); double price = rs.getDouble("selling_price");
int quantity = rs.getInt("quantity_sold"); int quantity = rs.getInt("quantity_sold");
@@ -116,36 +237,36 @@ public class SalesProductManagement extends JFrame {
String imagePath = rs.getString("image_path"); String imagePath = rs.getString("image_path");
ImageIcon icon = null; ImageIcon icon = null;
if(imagePath!=null && !imagePath.isEmpty()){ if (imagePath != null && !imagePath.isEmpty()) {
File imgFile = new File("images/"+imagePath); File imgFile = new File("images/" + imagePath);
if(imgFile.exists()){ if (imgFile.exists()) {
icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath()) icon = new ImageIcon(new ImageIcon(imgFile.getAbsolutePath())
.getImage().getScaledInstance(50,50,Image.SCALE_SMOOTH)); .getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
} }
} }
Object[] row = {icon,name,type,price,quantity}; Object[] row = {icon, name, type, price, quantity};
tableModel.addRow(row); tableModel.addRow(row);
} }
rs.close(); rs.close();
jdbc.close(); jdbc.close();
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
JOptionPane.showMessageDialog(this,"加载数据失败: "+e.getMessage()); JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage());
} }
} }
private void calculateTotal(){ private void calculateTotal() {
double total = 0.0; double total = 0.0;
for(int i=0;i<tableModel.getRowCount();i++){ for (int i = 0; i < tableModel.getRowCount(); i++) {
double price = Double.parseDouble(tableModel.getValueAt(i,3).toString()); double price = Double.parseDouble(tableModel.getValueAt(i, 3).toString());
int quantity = Integer.parseInt(tableModel.getValueAt(i,4).toString()); int quantity = Integer.parseInt(tableModel.getValueAt(i, 4).toString());
total += price*quantity; total += price * quantity;
} }
totalField.setText(String.format("%.2f 元",total)); totalField.setText(String.format("%.2f 元", total));
} }
public static void main(String[] args){ public static void main(String[] args) {
new SalesProductManagement("admin"); // 测试 admin new SalesProductManagement("admin"); // 测试 admin
} }
} }