ResultSet in JCombobox

坚强是说给别人听的谎言 提交于 2019-12-13 05:10:55

问题


I want to populate a Jcombobox with sql results but why am I getting an ArrayIndexOufOfBounds here? The JCombobox is like that: countrybox = new JComboBox(countries);

    int x = 0;
    String query = "SELECT UNIQUE country FROM criminals ORDER BY country ASC";
    System.out.println(query);
    Statement stmt = connection.createStatement();
    ResultSet rset = stmt.executeQuery(query);

    while (rset.next()) {
        countries[x] = rset.getString(1);
        x++;
      }

回答1:


No need for temporary storage. You can load the items directly into the combo box with out using an ArrayList:

comboBox.addItem(...);

Or use a Vector instead of the ArrayList because the DefaultListModel uses a Vector to hold the data anyway.




回答2:


Obviously the result set has more elements than the array countries. You should use an ArrayList which grows dynamically instead.

If you absolutely need an array after populating the ArrayList then you can obtain it from it using its method toArray.

EDIT

As suggested by @camickr JComboBox has a constructor which takes a Vector as parameter. Just like an ArrayList a Verctor can also grow automatically. So you can use it instead of the one which takes an array. Better yet, use the method addItem to add elements directly to the combobox.



来源:https://stackoverflow.com/questions/19199031/resultset-in-jcombobox

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