Search code examples
javaswingjcombobox

How To Initialize a JComboBox Whose Items are added Dynamically?


I have Created a JComboBox and its item are being added dynamically through a LinkedList, how to initialize its selected value.

Suppose "list" contains A->B->C->D->null

I want to intialize the ComboBox selected index with B (i.e 2nd Item In the list).

I have tried to do it as below

ComboBox.setSelectedIndex(1);

but I am getting 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);

Solution

  • Make sure elements are added into the comboBox, using addItem().

    Here's a small snippet:

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

    EDIT

    Adding from a linkedList

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

    enter image description here