Search code examples
javaswingmodelnullpointerexceptionjcombobox

Don't understand this NullPointerException with ComboBox


I can't understand why I'm getting this NullPointerException. I started with much different looking code (and improved to what you see) all in attempts of fixing the bug and I just can't figure out what's going on.

all help is hugely appreciated:

final JComboBox modelName = null;

//Model ComboBoxModel
final DefaultComboBoxModel termModel = new DefaultComboBoxModel(new String[]{
    "Choose One...", "Hypercom", "DejaVoo", "Nurit", "Verifone"});

...

// model drop-down      
    modelName.setModel(termModel);  //getting nullPointerException on this line

    modelName.addActionListener(this);              

    modelPanel.add(modelName);

...

@Override
public void actionPerformed(ActionEvent e) {
    if ("Hypercom".equals(modelName.getSelectedItem())){
        termName.setModel(hSpecModel);    
    } else if ("Deja Voo".equals(modelName.getSelectedItem())){
        termName.setModel(dSpecModel);    
    } else if ("Nurit".equals(modelName.getSelectedItem())){
        termName.setModel(nSpecModel);
    } else if ("Verifone".equals(modelName.getSelectedItem())){
        termName.setModel(vSpecModel);
    } else {
        termName.setModel(slctAbove);
    }
}

Solution

  • final JComboBox modelName = null; // !!!!!
    

    You really shouldn't wonder why you get a NPE when you try to use this variable:

    modelName.setModel(termModel);