Swing居中和设置系统风格

本文详细介绍了如何在Java应用中实现窗口居中显示,并调整系统风格以提升用户体验。通过获取屏幕尺寸和应用默认外观,我们能确保应用在不同分辨率和系统环境下都能优雅地展示。
//设置窗口居中
		int windowWidth = this.getWidth(); //获得窗口宽
		int windowHeight = this.getHeight(); //获得窗口高
		Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
		Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
		int screenWidth = screenSize.width; //获取屏幕的宽
		int screenHeight = screenSize.height; //获取屏幕的高
		this.setLocation(screenWidth / 2 - windowWidth / 2, screenHeight / 2 - windowHeight / 2);//设置窗口居中显示
		//设置系统风格
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

下面是一个 **增强版的体育商品管理系统**,整合了: - ✅ **MySQL 数据库存储数据** - ✅ **Swing 图形用户界面(GUI)** --- ### 🧩 功能说明 用户可以通过图形化窗口实现: - 添加、删除、修改、查询体育商品 - 所有数据存储在 MySQL 中 - 使用 JDBC 连接数据库 --- ## 🔧 第一步:创建 MySQL 数据库和表 ```sql CREATE DATABASE sports_store CHARACTER SET utf8mb4; USE sports_store; CREATE TABLE sports_product ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, price DECIMAL(10,2) NOT NULL, stock INT NOT NULL, category VARCHAR(50) ); ``` --- ## 📦 第二步:添加依赖(JDBC 驱动) 确保项目中包含 **MySQL JDBC Driver**。如果你使用的是普通 Java 项目,下载: 👉 [https://dev.mysql.com/downloads/connector/j/](https://dev.mysql.com/downloads/connector/j/) 然后将 `mysql-connector-j-x.x.x.jar` 添加到项目的类路径中。 > (如果是 Maven 项目,在 `pom.xml` 中加入) ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> ``` --- ## 💻 第三步:Java 完整代码(含 Swing + MySQL) ```java import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import java.util.Vector; public class SportsProductManagerGUI { private static final String DB_URL = "jdbc:mysql://localhost:3306/sports_store"; private static final String DB_USER = "root"; // 修改为你的用户名 private static final String DB_PASSWORD = "your_password"; // 修改为你的密码 private Connection conn; // GUI 组件 private JFrame frame; private JTextField idField, nameField, priceField, stockField, categoryField; private JTable productTable; private DefaultTableModel tableModel; public SportsProductManagerGUI() { initializeDB(); createGUI(); loadProducts(); } // 初始化数据库连接 private void initializeDB() { try { conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); System.out.println("✅ 数据库连接成功!"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "❌ 数据库连接失败:" + e.getMessage()); e.printStackTrace(); } } // 创建 GUI 界面 private void createGUI() { frame = new JFrame("🏀 体育商品管理系统"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(900, 600); frame.setLayout(new BorderLayout()); // 表单面板 JPanel formPanel = new JPanel(new GridLayout(6, 2, 10, 10)); formPanel.setBorder(BorderFactory.createTitledBorder("商品信息")); formPanel.add(new JLabel("商品ID:")); idField = new JTextField(); formPanel.add(idField); formPanel.add(new JLabel("名称:")); nameField = new JTextField(); formPanel.add(nameField); formPanel.add(new JLabel("价格:")); priceField = new JTextField(); formPanel.add(priceField); formPanel.add(new JLabel("库存:")); stockField = new JTextField(); formPanel.add(stockField); formPanel.add(new JLabel("类别:")); categoryField = new JTextField(); formPanel.add(categoryField); // 按钮面板 JPanel buttonPanel = new JPanel(new FlowLayout()); JButton addButton = new JButton("添加"); JButton updateButton = new JButton("修改"); JButton deleteButton = new JButton("删除"); JButton clearButton = new JButton("清空"); buttonPanel.add(addButton); buttonPanel.add(updateButton); buttonPanel.add(deleteButton); buttonPanel.add(clearButton); formPanel.add(new JLabel()); formPanel.add(buttonPanel); // 表格展示 String[] columns = {"ID", "名称", "价格", "库存", "类别"}; tableModel = new DefaultTableModel(columns, 0); productTable = new JTable(tableModel); productTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 双击行填充表单 productTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (e.getClickCount() == 2) { int row = productTable.getSelectedRow(); fillFormFromTable(row); } } }); JScrollPane scrollPane = new JScrollPane(productTable); // 添加组件到主窗口 frame.add(formPanel, BorderLayout.NORTH); frame.add(scrollPane, BorderLayout.CENTER); // 按钮事件绑定 addButton.addActionListener(e -> addProduct()); updateButton.addActionListener(e -> updateProduct()); deleteButton.addActionListener(e -> deleteProduct()); clearButton.addActionListener(e -> clearForm()); frame.setLocationRelativeTo(null); // 中显示 frame.setVisible(true); } // 填充表单(从表格双击) private void fillFormFromTable(int row) { if (row < 0) return; idField.setText(tableModel.getValueAt(row, 0).toString()); nameField.setText(tableModel.getValueAt(row, 1).toString()); priceField.setText(tableModel.getValueAt(row, 2).toString()); stockField.setText(tableModel.getValueAt(row, 3).toString()); categoryField.setText(tableModel.getValueAt(row, 4).toString()); } // 加载所有商品到表格 private void loadProducts() { tableModel.setRowCount(0); // 清空旧数据 String sql = "SELECT * FROM sports_product ORDER BY id"; try (PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Vector<String> row = new Vector<>(); row.add(String.valueOf(rs.getInt("id"))); row.add(rs.getString("name")); row.add(String.format("%.2f", rs.getDouble("price"))); row.add(String.valueOf(rs.getInt("stock"))); row.add(rs.getString("category")); tableModel.addRow(row); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "❌ 加载数据失败:" + e.getMessage()); e.printStackTrace(); } } // 添加商品 private void addProduct() { try { int id = Integer.parseInt(idField.getText().trim()); String name = nameField.getText().trim(); double price = Double.parseDouble(priceField.getText().trim()); int stock = Integer.parseInt(stockField.getText().trim()); String category = categoryField.getText().trim(); if (name.isEmpty() || category.isEmpty()) { JOptionPane.showMessageDialog(null, "❌ 名称和类别不能为空!"); return; } // 检查是否已存在该 ID if (productExists(id)) { JOptionPane.showMessageDialog(null, "❌ 该ID已存在,请更换ID!"); return; } String sql = "INSERT INTO sports_product (id, name, price, stock, category) VALUES (?, ?, ?, ?, ?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, id); stmt.setString(2, name); stmt.setDouble(3, price); stmt.setInt(4, stock); stmt.setString(5, category); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "✅ 商品添加成功!"); loadProducts(); clearForm(); } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "❌ 请输入有效的数字格式!"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "❌ 数据库错误:" + e.getMessage()); e.printStackTrace(); } } // 判断商品是否存在 private boolean productExists(int id) { try { String sql = "SELECT COUNT(*) FROM sports_product WHERE id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, id); ResultSet rs = stmt.executeQuery(); if (rs.next()) { return rs.getInt(1) > 0; } } } catch (SQLException e) { e.printStackTrace(); } return false; } // 修改商品 private void updateProduct() { try { int id = Integer.parseInt(idField.getText().trim()); String name = nameField.getText().trim(); double price = Double.parseDouble(priceField.getText().trim()); int stock = Integer.parseInt(stockField.getText().trim()); String category = categoryField.getText().trim(); if (name.isEmpty() || category.isEmpty()) { JOptionPane.showMessageDialog(null, "❌ 名称和类别不能为空!"); return; } if (!productExists(id)) { JOptionPane.showMessageDialog(null, "❌ 该ID的商品不存在!"); return; } String sql = "UPDATE sports_product SET name=?, price=?, stock=?, category=? WHERE id=?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, name); stmt.setDouble(2, price); stmt.setInt(3, stock); stmt.setString(4, category); stmt.setInt(5, id); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "✅ 商品修改成功!"); loadProducts(); clearForm(); } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "❌ 请输入有效的数字格式!"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "❌ 数据库错误:" + e.getMessage()); e.printStackTrace(); } } // 删除商品 private void deleteProduct() { try { int id = Integer.parseInt(idField.getText().trim()); if (!productExists(id)) { JOptionPane.showMessageDialog(null, "❌ 该ID的商品不存在!"); return; } int confirm = JOptionPane.showConfirmDialog(null, "确定要删除ID为 " + id + " 的商品吗?", "确认删除", JOptionPane.YES_NO_OPTION); if (confirm != JOptionPane.YES_OPTION) return; String sql = "DELETE FROM sports_product WHERE id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, id); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "✅ 商品删除成功!"); loadProducts(); clearForm(); } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "❌ 请输入有效的商品ID!"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "❌ 数据库错误:" + e.getMessage()); e.printStackTrace(); } } // 清空表单 private void clearForm() { idField.setText(""); nameField.setText(""); priceField.setText(""); stockField.setText(""); categoryField.setText(""); } // 主方法启动程序 public static void main(String[] args) { // 设置系统外观风格(可选) try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel()); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(() -> new SportsProductManagerGUI()); } } ``` --- ### ✅ 功能亮点 | 功能 | 说明 | |------|------| | 🔗 MySQL 存储 | 数据持久化,重启不丢失 | | 🖱️ 双击编辑 | 在表格中双击某行,自动填充到表单 | | 🛡️ 输入校验 | 防止空值、非法数字输入 | | 🗑️ 删除确认 | 弹窗确认防止误删 | | 🔄 实时刷新 | 增删改后自动重新加载表格 | --- ### ⚠️ 注意事项 1. 修改以下变量为你的实际数据库信息: ```java private static final String DB_USER = "root"; private static final String DB_PASSWORD = "your_password"; ``` 2. 确保 MySQL 服务正在运行,默认端口是 `3306` 3. 推荐使用 IDE 如 IntelliJ IDEA 或 Eclipse,并正确导入 JDBC 驱动 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值