java - JComboBox error when items are added -
i try add items jcombobox , receive nullpointerexception error. sample of code :
public adminpanel() { fillcomboteacher(); initcomponents(); } public void fillcomboteacher(){ hashset<person> set = cont1.returnteachers(); iterator = set.iterator(); try { while (it.hasnext()) { person p = (person) it.next(); string name = p.getname(); comboteacher.additem(name); } } catch (exception e) { system.out.println(e); } } person class - name, state (with getters , setters)
returnteachers() - returns hashset containing persons state = "teacher"
i don't understand why i'm receiving error , why can't fill combobox, followed tutorial step-by-step , still not well. thanks!
you calling fillcomboteacher before calling initcomponents.
looking @ method's name, assumed initialized comboteacher in latter.
so @ point (comboteacher.additem(name);), comboteacher not yet initialized , hence nullpointerexception.
to fix this, swap 2 method calls in constructor initialize components before trying use them.
few notes:
a
nullpointerexceptioneasy fix. @ stacktrace (it indicates line npe occurs) , see can null , why @ line.don't use raw iterator, generic 1 (
iterator<person> = set.iterator();), avoid cast object returnednext()call.since reading elements in set, can use for-each loop
for(person p : cont1.returnteachers()) comboteacher.additem(p.getname());
Comments
Post a Comment