如何链接两个jcomboboxes而不重复这些值

时间:2016-09-22 21:47:59

标签: java swing jdbc combobox

我想从comboBox中选择一个名为comboBox的项目在comboBox asnaf中显示项目..我做了但是项目出现了两次,当我从comboBox名称中选择另一项时,其他项目作为As附加在前面的项目上它显示在上图中..这是我的代码

 public void agent_comboBoxA() {
    try {

        String sql = "select * from `trading`";
        myStmt = connection.prepareStatement(sql);
        rs = myStmt.executeQuery();
        while (rs.next()) {
            String agent = rs.getString("agent_name");
            names.addItem(agent);

        }

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

 public void kind_comboBoxA()
{
    String sql = "select kind from trading where agent_name = ?";


    try {

        myStmt = connection.prepareStatement(sql);
        myStmt.setString(1,String.valueOf(names.getSelectedItem()));
        rs = myStmt.executeQuery();
        while (rs.next()) {
            String kind = rs.getString("kind");
            asnaf.addItem(kind);
        }
    }catch (SQLException e) {
        e.printStackTrace();
    }
}

public the defualt Constructor {

        agent_comboBoxA();

        names.addItemListener(e -> {
            kind_comboBoxA();
        });
    }

this when repeat the same value

this when repeat the same value and the other value

1 个答案:

答案 0 :(得分:3)

  

其他项目附加在之前的项目上

在开始添加新项目之前,您需要删除旧项目。

请参阅removeAllItems() API中的JComboBox方法。