JComboBox only show one item from database

♀尐吖头ヾ 提交于 2019-12-02 05:51:41

问题


I'm trying to display database item into a JComboBox and this is my code.

public static void checkItemName(){
    Connection conn = SQLite.SQLite();
    String sql = "select itemname from item";
    try{
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            String list = resultSet.getString("itemname");
            purcItemName.addItem(list);
            conn.close();
        }
    } catch (SQLException lol){
        System.out.println(lol.toString());
    }

}

I did declare static JComboBox purcItemName; and purcItemName = new JComboBox();

The method/function will be called then user press login button.

The problem I'm having now is that, it only shows one item while my database has multiple items.

Anyone got an idea why?


回答1:


        Vector v = new Vector();
        while (resultSet.next()){
            String list = resultSet.getString("itemname");
            v.add(list);

        }
        conn.close();
        purcItemName.setModel(new DefaultComboBoxModel(v));

store the data you got from database in a vector object and once that is completed set the vector object in your combobox as a new model. try this one and don't close the connection inside your loop.




回答2:


you are closing connection inside resultSet.next() check, put the conn.close() outside, to the end



来源:https://stackoverflow.com/questions/36808057/jcombobox-only-show-one-item-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!