将数据加载到组合框

时间:2015-11-12 02:38:24

标签: java swing

我有两个组合框.1是主要部门,另一个是子部门。我想将Main_department表中的所有数据加载到组合框中。当选择组合框项目时,我想加载与该选定项目相关的子部门。

try {
    Conn c=new Conn();
    Statement s=c.createConn().createStatement();

    String query ="SELECT * FROM main_dep";
    ResultSet rst = s.executeQuery(query);
    DefaultComboBoxModel dc=(DefaultComboBoxModel)maindep.getModel();

    while(rst.next()){
        dc.addElement(rst.getString(2));
    }

} catch (Exception e) {
    e.printStackTrace();
}

这就是我得到主要部门的方式。然后我在主要部门组合框中为itemStateChange事件编写了以下代码。

 String main = maindep.getSelectedItem().toString();
            Conn c=new Conn();
          try {
                //Conn c=new Conn();
                Statement s=c.createConn().createStatement();

                String query ="SELECT Description FROM sub_dep WHERE Main_dep_ID IN (SELECT Main_Dep_Id FROM main_dep WHERE description = '"+main+"')";
                ResultSet rst = s.executeQuery(query);
                DefaultComboBoxModel dc=(DefaultComboBoxModel)subdep.getModel();

                while(rst.next()){
                    dc.addElement(rst.getString(1));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

当主要部门被更改时,与该部门相关的子部门被加载到子部门组合框。但是当选择另一个时,加载的项目仍然存在。

我如何克服这个问题?

2 个答案:

答案 0 :(得分:1)

  

但是当选择了另一个时,加载的项目仍然存在

您可以使用:

dc.removeAllElements();

在开始向模型添加新元素之前。

答案 1 :(得分:0)

此案例调用依赖的组合框。 你必须先将数据加载到第一个组合框,然后当用户选择该组合框的值时,它会将Ajax或其他技术返回到服务器以将数据检索到第二个组合框。所以,这就是想法。 您可以看到此链接以供参考here

相关问题