我目前正在编写一个使用查询填充的jcombobox的Java程序。我想知道程序执行时是否有办法获得默认的选定值。我的查询是按字母顺序列出的语言列表,但我很好奇是否可以将英语(位于列表中间)作为默认值。
我知道当您手动将值硬编码到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);
}
感谢您的时间。
答案 0 :(得分: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));
}
}
顺便说一句:你应该清理那些代码,不是那么好。