java 在由查询填充的 jcombobox 中设置默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11762249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:16:52  来源:igfitidea点击:

Setting a default value in a jcombobox populated by a query

javaswingjcombobox

提问by SamiSunshine

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.

我目前正在用 Java 编写一个程序,该程序使用一个查询填充的 jcombobox。我想知道是否有办法在程序执行时有一个默认的选定值。我的查询是按字母顺序列出的语言列表,但我很好奇是否可以将英语(位于列表中间)作为默认值。

I know that when you manually hard code the values into the jcombobox you can set the default variable as

我知道当您手动将值硬编码到 jcombobox 中时,您可以将默认变量设置为

jcombobox.setSelectedIndex(int anIndex);

or

或者

jcombobox.setSelectedItem(Object anObject);

but I am unsure when a ResultSet loops and populates the jcombobox.

但我不确定 ResultSet 何时循环并填充 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.

感谢您的时间。

采纳答案by Angelo Fuchs

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.

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