基于Java swing+Mysql实现的超市管理与购物系统,使用了beautyEye_inf.jar美化界面
由于代码量较大,我将提供一个核心函数的示例,展示如何使用Java Swing和JDBC连接MySQL数据库来实现超市管理系统中商品的查询功能。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class SupermarketSystem extends JFrame {
private JTextField searchField;
private JTable productTable;
private JScrollPane scrollPane;
public SupermarketSystem() {
// 初始化界面组件
searchField = new JTextField();
productTable = new JTable();
scrollPane = new JScrollPane(productTable);
// 设置布局管理器
setLayout(new BorderLayout());
// 添加搜索框和表格到界面
add(searchField, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
// 搜索框的按键监听,用于查询商品
searchField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
String searchQuery = searchField.getText();
updateProductTable(searchQuery);
}
});
// 设置窗口属性
setTitle("超市管理与购物系统");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void updateProductTable(String searchQuery) {
String sql = "SELECT * FROM products WHERE name LIKE ?";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/supermarket", "username", "password");
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "%" + searchQuery + "%");
try (ResultSet rs = pstmt.executeQuery()) {
// 创建表格模型,填充数据
DefaultTableModel model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Price");
while (rs.next()) {
model.addRow(new Object[]{
rs.getInt("id"),
rs.getString("name"),
rs.getDouble("price")
});
}
productTable.setModel(model);
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "数据库查询错误:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
// 使用事件分发线程确保界面更新在事件调度线程中
Swin
评论已关闭