我有一个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();
}
你可以帮帮我吗?
谢谢..
答案 0 :(得分:2)
您可以通过这种方式自动刷新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
。
答案 1 :(得分:1)
Inzimam Tariq IT&#39的代码(上图):
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);
}
我建议将所有这些代码放在ActionListener
中。因此,每次在comboBox
上输入鼠标时,上述代码都将运行。您应该执行以下操作:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
我建议使用mouseListener
:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
但是如果你想看看其他ActionListeners
,你可以在这里看到它们:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
答案 2 :(得分:0)
在数据库中添加新注册表后,执行removeAllItems comboBox.removeAllItems();并重新组合de combobox, 我的例子:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");