编程语言
首页 > 编程语言> > java-在查询填充的jcombobox中设置默认值

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

作者:互联网

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

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

jcombobox.setSelectedIndex(int anIndex);

要么

jcombobox.setSelectedItem(Object anObject);

但是我不确定ResultSet何时循环并填充jcombobox.

目前,我的代码是:

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

感谢您的时间.

解决方法:

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

顺便说一句:您应该清理该代码,那样不好.

标签:jcombobox,swing,java
来源: https://codeday.me/bug/20191201/2077322.html