Setting a default value in a jcombobox populated by a query
11,265
ResultSet rs = statement.executeQuery("select language from language order by 1");
while (rs.next()) {
langbox.addItem(rs.getString(1));
//I'm thinking that this is where a default value would be located
if(rs.getString(1).equals(myDefaultLanguageVariable)) {
langbox.setSelectedItem(rs.getString(1));
}
}
btw: You should clean up that code, its not good that way.
Author by
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
I am currently writing a program in Java that uses a query populated jcombobox. I was wondering if there is a way to have a default selected value when the program executes. My query is a list of languages listed alphabetically, but I am curious if it is posible to have English (which is in the middle of the list) be the default value.
I know that when you manually hard code the values into the jcombobox you can set the default variable as
jcombobox.setSelectedIndex(int anIndex);
or
jcombobox.setSelectedItem(Object anObject);
but I am unsure when a ResultSet loops and populates the jcombobox.
Currently my code is:
languageLabel =new JLabel("Languages:"); rowFour.add(languageLabel,BorderLayout.WEST);//adding to my current panel langbox = new JComboBox(); rowFour.add(langbox,BorderLayout.WEST); try { con = DriverManager.getConnection ("jdbc:oracle:thin:@localHost:portNumber:ORCL", "username", "password"); statement = con.createStatement(); } catch(SQLException sqle) { System.out.println(sqle); } langbox.removeAllItems(); langbox.addItem("Please Select..."); try { ResultSet rs = statement.executeQuery("select language from language order by 1"); while (rs.next()) { langbox.addItem(rs.getString(1)); //Thinking that this is where a default value would be located } } catch(Exception e) { System.err.println(e); }
Thank you for your time.