1

我将 2 个 JComboBox 组件添加到我的 GUIproductComboBoxcategoryComboBox中,并为每个组件定义了以下项目侦听器:

    categoryComboBox.addItemListener(new GoItemListener());
    productComboBox.addItemListener(new ProductItemListener());

用户首先选择一个产品,然后侦听器应根据选择的产品填充类别框。我的项目监听器是内部类。

ProductItemListener调用如下所示的方法populateCategories

    protected void populateCategories() {
        String product = productComboBox.getSelectedItem().toString();

        myMediaDataAccessor.init(product);

        ArrayList categoryArrayList = null;
        categoryArrayList = myMediaDataAccessor.getCategories();

        Iterator iterator = categoryArrayList.iterator();
        String aCategory;
        while (iterator.hasNext()) {
            aCategory = (String) iterator.next();
            categoryComboBox.addItem(aCategory.toString());
        }
    }

我的productComboBox音乐和视频中有两个产品项目。如果我选择音乐,那么我categoryComboBox会使用 ArrayList 中的字符串正确填充。

问题是,如果我选择视频,我的categoryArrayList包含正确的 ArrayList 字符串,所以我的数据被返回并似乎添加到了categoryComboBox,因为我没有收到任何异常,只是我categoryComboBox从 GUI 中消失了。

有任何想法吗?
谢谢

4

1 回答 1

1

根据您发布的随机代码,很难猜出您在做什么,并且给您 25% 的接受率,我不确定当您似乎不欣赏您收到的建议时我是否应该回答。

无论如何,这就是我分享两个相关组合框的方式:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener
{
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable subItems = new Hashtable();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox( items );
        mainComboBox.addActionListener( this );

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

        //  Create sub combo box with multiple models

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

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
    }

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

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
     }
}

如果您需要更多帮助,请发布显示问题的SSCCE 。

于 2009-12-11T00:52:04.167 回答