1

I currently have 2 JComboBoxes. When an item in the first JComboBox is selected, relevant items are displayed in JComboBox2. However when I try to select the items in the second JComboBox it keeps returning to default. However it is registering the value of the item that is selected, just not displaying the selected item in the JComboBox.

Here is a snippet of my code:

mainComboBox = new JComboBox( treeItems);
    mainComboBox.addActionListener( this );


    getContentPane().add( mainComboBox, BorderLayout.WEST );

    //  Create sub combo box with multiple models

    subComboBox = new JComboBox();
    subComboBox.addActionListener(this);


    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    getContentPane().add( subComboBox, BorderLayout.EAST );

    String [] chromalveolataItems = chromalveolataTreeSet.toArray(new String[chromalveolataTreeSet.size()]);
    subItems.put(treeItems[1], chromalveolataItems);

    String [] mycetozoaItems = mycetozoaTreeSet.toArray(new String[mycetozoaTreeSet.size()]);
    subItems.put(treeItems[2], mycetozoaItems);

    String [] metazoaItems = metazoaTreeSet.toArray(new String[metazoaTreeSet.size()]);
    subItems.put(treeItems[3], metazoaItems);

    String [] viridiplantaeItems = viridiplantaeTreeSet.toArray(new String[viridiplantaeTreeSet.size()]);
    subItems.put(treeItems[4], viridiplantaeItems);

    String [] virusesItems = virusesTreeSet.toArray(new String[virusesTreeSet.size()]);
    subItems.put(treeItems[5], virusesItems);

.

@Override
public void actionPerformed(ActionEvent e)
{
    String item = (String)mainComboBox.getSelectedItem();
    Object o = subItems.get( item );

   String organismComboItem = (String)subComboBox.getSelectedItem();

   if(treeArray.contains(organismComboItem)){          
       //System.out.println(treeArray.indexOf(organismComboItem));
       String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
       System.out.println(selectedId);

             }

    if (o == null)
    {
        subComboBox.setModel( new DefaultComboBoxModel() );
    }

    else
    {
        subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );

    }
}

There is probably a relatively simple solution to this however I am new to Java so please forgive me.

Any help whatsoever would be much appreciated! :)

Matt
  • 23
  • 4

1 Answers1

0

Looks to me like you based your code on the example found in this posting: Binding comboboxes in swing (or one like it).

When you use examples don't add extra code.

subComboBox.addActionListener(this);

The example does not do this. By adding the same listener to the subComboBox you are telling it to reset itself every time you select an item from it. Only the mainComboBox needs the ActionListener.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288