使用ComboBox填充ComboBox

时间:2014-10-14 16:20:36

标签: java combobox

我在这里遇到问题,而不是替换combobox2中的项目,它会堆叠。我试图把bookss.removeAllItems();在bookss.addItem(名字)之上;但每当我点击combobox1中的其他项目时,我都会收到错误。

这是我的代码

String caa = categorys.getSelectedItem().toString();
if ("Fiction".equals(caa))
{
    String acct = categorys.getSelectedItem().toString();
    try{
        pst = con.prepareStatement("select * from books where category=?");
        pst.setString(1, acct);
        ResultSet rsf = pst.executeQuery();
        rsf.next();
        try{
            rsf = stmt.executeQuery("select * from BOOKS WHERE category='Fiction'");
            while(rsf.next())
            {
                String names = rsf.getString("book_title");
                bookss.addItem(names);
            }
            }catch(SQLException err){
            System.out.println(err);
        }
        }catch(SQLException e){
        JOptionPane.showMessageDialog(null, e);
    }
}
if ("Horror".equals(caa))
{
    String acct = categorys.getSelectedItem().toString();
    try{
        pst = con.prepareStatement("select * from books where category=?");
        pst.setString(1, acct);
        ResultSet tts = pst.executeQuery();
        tts.next();
        try{
            tts = stmt.executeQuery("select * from BOOKS WHERE category='Horror'");
            while(tts.next())
            {
                String names = tts.getString("book_title");
                bookss.addItem(names);
            }
            }catch(SQLException err){
            System.out.println(err);
        }
        }catch(SQLException e){
        JOptionPane.showMessageDialog(null, e);
    }
}

1 个答案:

答案 0 :(得分:0)

使用此:

DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();