供参考:
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class ComboBoxTable extends JFrame {
private JComboBox<String> comboBox;
private JTable table;
private DefaultTableModel tableModel;
private Connection connection;
private Statement statement;
private ResultSet resultSet;
public ComboBoxTable() {
super("ComboBox Table");
// 创建连接数据库的代码
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT DISTINCT ip FROM table");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Unable to connect to database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
// 创建选项框
comboBox = new JComboBox<>();
comboBox.addItem("All");
try {
while (resultSet.next()) {
String ip = resultSet.getString("ip");
comboBox.addItem(ip);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Unable to read data from database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
// 创建表格
table = new JTable();
tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("IP");
tableModel.addColumn("Data");
table.setModel(tableModel);
// 将选项框和表格放入面板中
JPanel panel = new JPanel(new BorderLayout());
panel.add(comboBox, BorderLayout.NORTH);
panel.add(new JScrollPane(table), BorderLayout.CENTER);
// 将面板添加到窗口中
getContentPane().add(panel);
// 注册选项框的事件处理程序
comboBox.addActionListener(e -> {
String selectedItem = comboBox.getSelectedItem().toString();
try {
if (selectedItem.equals("All")) {
// 如果选中“全部”选项,则显示所有行
resultSet = statement.executeQuery("SELECT * FROM table");
} else {
// 否则,只显示与选中的IP地址相同的行
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM table WHERE ip = ?");
preparedStatement.setString(1, selectedItem);
resultSet = preparedStatement.executeQuery();
}
// 清空表格
tableModel.setRowCount(0);
// 将结果集中的行添加到表格中
while (resultSet.next()) {
int id = resultSet.getInt("id");
String ip = resultSet.getString("ip");
String data = resultSet.getString("data");
tableModel.addRow(new Object[]{id, ip, data});
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Unable to read data from database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
});
// 设置窗口大小、可见性和关闭操作
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new ComboBoxTable();
}
}