Part of the answer references GPT, GPT_Pro to better solve the problem
To implement this feature, first need to prepare a Jcombobox in Swing, Then we need to set up a listening event, which is used to monitor whether the content in Jcombobox changes. Once it changes, we will perform some actions, such as finding the ip address selected in Jcombobox from the database and displaying it in Jtable.
We can use java.sql.Connection, java.sql.Statement, java.sql.ResultSet and other classes to connect to the database, and realize the database query.
The specific code implementation can be divided into two steps:
-
Monitor content changes in Jcombobox
//定义一个Jcombobox
JComboBox comboBox=new JComboBox();
//往Jcombobox中放入ip地址的选项
comboBox.addItem("显示全部");
comboBox.addItem("192.168.01");
comboBox.addItem("192 168.02");
comboBox.addItem("192 168.03");
//新建一个监听事件,当Jcombobox的选项发生变化的时候就触发这个事件
comboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//TODO:在这里添加你要执行的代码
}
});
-
Executes database query code in listening event
//获取当前Jcombobox中选中的ip地址
String ipAddress=comboBox.getSelectedItem().toString();
//如果是显示全部,则不用进行数据库查询,而是直接把数据库中所有的行显示到Jtable中去
if(!"显示全部".equals(ipAddress)){
//新建一个Connection对象,用于连接数据库
Connection conn=DriverManager.getConnection(url, username, password);
//定义sql语句,根据ip地址来查询table表里的内容
String sql="select * from table where ipaddress=?";
//新建一个PreparedStatement对象,用于执行sql语句
PreparedStatement pstmt=conn.prepareStatement(sql);
//将ip地址赋值到sql语句中
pstmt.setString(1, ipAddress);
//执行sql语句,并将结果集存储到ResultSet对象中去
ResultSet rs=pstmt.executeQuery();
//新建一个DefaultTableModel对象,用于存储从数据库中获得的数据
DefaultTableModel dtm=new DefaultTableModel();
//将ResultSet对象里的数据存储到DefaultTableModel对象里去
while (rs.next()){
Vector v = new Vector(); //新建一个Vector对象用于存储一行数据
//将ResultSet里的id、ip地址、数据依此存储到Vector对象里去
v.add(rs.getString("id"));
v.add(rs.getString("ipaddress"));
v.add(rs.getString("data"));
//将Vector对象存储到DefaultTableModel里去
dtm.addRow(v);
}
//将DefaultTableModel对象作为参数传递给Jtable
jtable.setModel(dtm);
//关闭ResultSet、PreparedStatement、Connection对象
rs.close();
pstmt.close();
conn.close();
}else{
//TODO:如果是显示全部,则要将数据库中所有的行显示到Jtable中去
}
If the answer is helpful, please accept it.