gpt4 book ai didi

java - 如何在更新后自动刷新 jComboBox 数据?

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:30 25 4
gpt4 key购买 nike

我有一个 jComboBox 从 MySQL 服务器数据库获取数据。

当我向数据库添加新数据时,jComboBox 不显示它,我必须重新打开我的程序以将新数据添加到 jComboBox

如何自动刷新jComboBox数据?

这是我的代码:

private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}


private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);

while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}


//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}

你能帮帮我吗?

谢谢你..

最佳答案

你可以这样做它会自动刷新 combobox

try {
comboBox.removeAllItems();

sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);

while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}

removeAllItems(); 方法将清除组合框以确保不重复值。
您不需要创建一个单独的 Object 来添加到 jComboBox 中,您也可以添加 String

关于java - 如何在更新后自动刷新 jComboBox 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com