3

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.

4

1 回答 1

3
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));
   }
}

顺便说一句:你应该清理那个代码,那样不好。

于 2012-08-01T15:16:22.597 回答