尝试迭代HashMap并添加到JComboBox

时间:2015-03-09 10:39:25

标签: java

我正在尝试遍历HashMap并将内容添加到ComboBox。但是,它会触发null错误。

ComboBoxModel jComboBox1Model = 
                        new DefaultComboBoxModel();


            Iterator it = cashCheckout.products.keySet().iterator();
            while(it.hasNext())
            {
                jComboBox1.addItem(cashCheckout.products.get(it.next()));
            }

            jComboBox1 = new JComboBox();
            getContentPane().add(jComboBox1);


            jComboBox1.setModel(jComboBox1Model);
            jComboBox1.setBounds(362, 139, 111, 22);

CashCheckout:

public class Checkout {
    //Add Products class to the Checkout
    Products pd = new Products();
    //Add the Hashmaps that were created in Products class.
    HashMap<String, ProductDetails> products = pd.getProductsHashmap();
    HashMap<String, ProductDetails> scanned = pd.getScannedHashmap();

然后,GUI会触发addItem行处抱怨的错误。 NullPointerException,即使填充了此HashMap。这是为什么?

2 个答案:

答案 0 :(得分:2)

jComboBox1没有初始化。在尝试填充它之后初始化它。

将您的代码更改为:

        jComboBox1 = new JComboBox();
        Iterator it = cashCheckout.products.keySet().iterator();
        while(it.hasNext())
        {
            jComboBox1.addItem(cashCheckout.products.get(it.next()));
        }

答案 1 :(得分:0)

移动线

jComboBox1 = new JComboBox();

到上面你首先使用jComboBox 1,shop>

jComboBox1 = new JComboBox();
Iterator it = cashCheckout.products.keySet().iterator();
while(it.hasNext())
{
    jComboBox1.addItem(cashCheckout.products.get(it.next()));
}