Java可视化商品查询器代码
时间: 2023-07-03 09:03:55 浏览: 86
以下是一个简单的Java可视化商品查询器代码示例,它使用Java Swing库来创建GUI界面,并使用JDBC连接到MySQL数据库以查询商品信息:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ProductSearcher extends JFrame implements ActionListener {
private JTextField tfId, tfName, tfPrice;
private JButton btnSearch;
private Connection conn;
private PreparedStatement pstmt;
public ProductSearcher() {
// 设置窗口标题和大小
setTitle("商品查询器");
setSize(400, 150);
// 创建界面元素
JLabel lbId = new JLabel("商品编号:");
JLabel lbName = new JLabel("商品名称:");
JLabel lbPrice = new JLabel("商品价格:");
tfId = new JTextField(10);
tfName = new JTextField(10);
tfPrice = new JTextField(10);
btnSearch = new JButton("查询");
// 创建界面布局
JPanel pnId = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnId.add(lbId);
pnId.add(tfId);
JPanel pnName = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnName.add(lbName);
pnName.add(tfName);
JPanel pnPrice = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnPrice.add(lbPrice);
pnPrice.add(tfPrice);
JPanel pnButton = new JPanel(new FlowLayout(FlowLayout.CENTER));
pnButton.add(btnSearch);
JPanel panel = new JPanel(new GridLayout(4, 1));
panel.add(pnId);
panel.add(pnName);
panel.add(pnPrice);
panel.add(pnButton);
// 添加事件监听
btnSearch.addActionListener(this);
// 显示界面
add(panel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 建立数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSearch) {
try {
pstmt = conn.prepareStatement("SELECT * FROM products WHERE id = ?");
pstmt.setInt(1, Integer.parseInt(tfId.getText()));
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
tfName.setText(rs.getString("name"));
tfPrice.setText(rs.getDouble("price") + "");
} else {
JOptionPane.showMessageDialog(null, "未找到该商品!");
}
} catch (NumberFormatException | SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "查询失败!");
}
}
}
public static void main(String[] args) {
new ProductSearcher();
}
}
```
在此示例中,我们首先创建了一个包含文本框和按钮的GUI界面。然后,我们在构造函数中建立了一个JDBC连接,并在按钮的事件监听器中执行了SQL查询以获取商品信息。最后,我们将查询结果显示在GUI界面上。
阅读全文