gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:26 24 4
gpt4 key购买 nike

我目前正在用 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));
}
}

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

关于java - 在由查询填充的 jcombobox 中设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11762249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com