如何初始化动态添加项目的JComboBox?

时间:2015-06-15 11:31:14

标签: java swing jcombobox

我创建了一个JComboBox,其项目是通过LinkedList动态添加的,如何初始化其选定的值。

假设"list"包含A->B->C->D->null

我想用 B (即列表中的第二项)初始化 ComboBox 选定的索引。

我试过这样做

ComboBox.setSelectedIndex(1);

但我得到了Exception setSelectedIndex: 1 out of bound

JComboBox ComboBox= new JComboBoX();
LinkedList List = new LinkedList();

getListDataFromDataBase();
//After this List Contains A->B->C->D->null

for(int i=1;i<=List.getSize();i++)
{
    Object Item = List.getValueAt(i);
    ComboBox.addItem(Item);
}

ComboBox.setSelectedIndex(1);

1 个答案:

答案 0 :(得分:2)

确保使用comboBox将元素添加到addItem()

这是一个小片段:

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Demo {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox jComboBox1 = new JComboBox();
    jComboBox1.addItem("Item 0");
    jComboBox1.addItem("Item 1");
    jComboBox1.addItem("Item 2");
    jComboBox1.addItem("Item 3");
    jComboBox1.addItem("Item 4");
    jComboBox1.addItem("Item 5");

    Object cmboitem = jComboBox1.getSelectedItem();
    System.out.println(cmboitem);

    frame.add(jComboBox1);

    jComboBox1.setSelectedIndex(4);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

修改

linkedList

添加
for(int i = 0; i < linkedList.size(); i++)
   comboBox.addItem(linkedList.get(i).toString());

enter image description here