问题
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