【问题标题】:Display selected Item in JComboBox when item is clicked单击项目时在 JComboBox 中显示选定的项目
【发布时间】:2015-09-26 09:15:22
【问题描述】:

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

这是我的代码的 sn-p:

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 新手,所以请原谅我。

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

【问题讨论】:

    标签: java jcombobox


    【解决方案1】:

    在我看来,您的代码是基于此帖子中的示例:Binding comboboxes in swing(或类似的)。

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

    subComboBox.addActionListener(this);
    

    该示例没有这样做。通过向 subComboBox 添加相同的侦听器,您可以告诉它在每次从中选择项目时自行重置。只有 mainComboBox 需要 ActionListener。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      相关资源
      最近更新 更多