我试图遍历HashMap并将内容添加到ComboBox。但是,它会引发空错误。
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。为什么是这样?
最佳答案
jComboBox1
尚未初始化。您尝试填充它后,对其进行初始化。
将您的代码更改为:
jComboBox1 = new JComboBox();
Iterator it = cashCheckout.products.keySet().iterator();
while(it.hasNext())
{
jComboBox1.addItem(cashCheckout.products.get(it.next()));
}