hk96 hk96 - 7 months ago 63
Java Question

JComboBox only show one item from database

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?

Answer
        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.

Comments