单击项目时,在JComboBox中显示所选项目

时间:2015-07-08 12:41:56

标签: java jcombobox

我目前有2个JComboBox。选择第一个JComboBox中的项目时,相关项目将显示在JComboBox2中。但是,当我尝试选择第二个JComboBox中的项时,它会一直返回默认值。但是它正在注册所选项目的值,而不是在JComboBox中显示所选项目。

以下是我的代码片段:

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

    }
}

这可能是一个相对简单的解决方案但是我是Java新手所以请原谅我。

任何帮助都将不胜感激! :)

1 个答案:

答案 0 :(得分:0)

在我看来,您希望根据此帖子中的示例找到您的代码:Binding comboboxes in swing(或类似的人)。

使用示例时,请不要添加额外的代码。

subComboBox.addActionListener(this);

该示例不执行此操作。通过向subComboBox添加相同的侦听器,您告诉它每次从中选择一个项目时都会重置它。只有mainComboBox需要ActionListener。

相关问题