java - 从数据库中获取值后如何清除 jComboBox

标签 java swing jdbc jcombobox comboboxmodel

谁能帮我解决这段代码?

在此处输入代码 我想问的是,当从代码中的 jComboBox3 中选择另一个值时,如何清除 JcbSub(jComboBox):

1 private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {
2    Connection con;
3    Statement stmt;
4    try {
5        
6        Class.forName("sun.jdbc.odbc.JdbcOdbc");
7    } catch (ClassNotFoundException ex) {
8        JOptionPane.showMessageDialog(null, ex);
9    }
10    try {
11       con= DriverManager.getConnection("Jdbc:Odbc:food");
12        stmt= con.createStatement();
13        String sql="select i_name from food where category= '"+ jComboBox3.getSelectedItem().toString()+"'";
14        ResultSet RS= stmt.executeQuery(sql);
15        JcbSub.setSelectedItem("");
16        while(RS.next()){
17            
18            JcbSub.addItem(RS.getString("i_name"));
19            
20            
21        }
22        
23       
24        
25    } catch (SQLException ex) {
26        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
27    }
28    
29    
30   
31 }

最佳答案

你必须这样做

 private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {
    Connection con;
    Statement stmt;
 try {

    Class.forName("sun.jdbc.odbc.JdbcOdbc");
} catch (ClassNotFoundException ex) {
    JOptionPane.showMessageDialog(null, ex);
 }
  //add this to remove all Items
     JcbSub.removeAllItems();
 if(jComboBox3.getSelectedItem() == 0) {
  try {


     con= DriverManager.getConnection("Jdbc:Odbc:food");
     stmt= con.createStatement();
     String sql="select i_name from food where category= '"+jComboBox3.getSelectedItem().toString()+"'";
     ResultSet RS= stmt.executeQuery(sql);
     JcbSub.setSelectedItem("");
     while(RS.next()){

        JcbSub.addItem(RS.getString("i_name"));


    }



} catch (SQLException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

}else if(jComboBox3.getSelectedItem()  == 1) {
//etc... 
}
// or use Switch case    

}

关于java - 从数据库中获取值后如何清除 jComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16858765/

相关文章:

java lwjgl 如何让鼠标不可见

java - 将 webapp 从 Eclipse 部署到 Tomcat 根上下文

java - 当我尝试运行该类时出现 Java 安全错误

java - 如何重用 JDBC 语句并自动关闭结果集?

mysql - 将 XA 事务与 JDBC、MySQL 和 Microsoft SQL Server 结合使用

java - 选择 "tab"时执行操作

java - 在 java -jar 执行时指定 javax.net.ssl.trustStore 选项

java - JList.getModel() ClassCastException 异常

java - 将状态栏添加到 JFrame 时出现问题

java - 使用java导入mysql时跳过数据中的重复行