java - Dynamically update JComboBox (NullPointerException) -


i'm trying dynamically update jcombobox in swing application , getting null pointer exception.

class accounts extends jpanel {      jcombobox<string> accountselect;     defaultcomboboxmodel accountselectmodel;   public accounts() {     this.initgui();   }   public void initgui() {    //setlayout etc...     string[] al = {};//start empty    this.accountselectmodel = new defaultcomboboxmodel(al);     this.accountselect = new jcombobox<string>();      this.accountselect.setmodel(accountselectmodel);     this.add(this.accountselect);  }  public void updatecombobox(string[] al) {   //clear items , apply new   this.accountselectmodel = new defaultcomboboxmodel(al);   this.accountselect.setmodel(this.accountselectmodel);  }   public void removecomboboxitems() {     //a call here here resorts in null exception pointer ???     this.accountselectmodel.removeallelements();    }   } 

thanks feedback.

update

figured out problem. sure wasn't problem (sorry not putting in code).

i adding listener via addactionlistener (inside accounts) accountselect combobox.

  this.accountselect.addactionlistener(new acountactionlistener);  class acountselectlistener implements actionlistener {    void actionperformed(actionevent e) p     //object source etc..     if(source == accountselect) {       //etc...       selectaccount(item);     }   }  } 

instead, i'm doing:

class accounts extends jpanel implements actionlistener  

and overriding actionperformed method inside accounts.

this solved issue...

update 2

however, prefer (as others have recommended) don't have make entire accounts class actionlistener.

so went original , found problem each call this.accountselectmodel.removeallelements triggered action in inner accountselectlistener added this.accountselect.

the listener meant set new combo box option, since wasn't called @ time select change occurred (but on removeallelements), object source (item) null when passed threw npe.

avoid calling public methods in constructor. in particular, check whether you're calling removecomboboxitems() listener added before accounts constructor finishes, might happen if fail construct swing gui objects on event dispatch thread. default, value of accountselectmodel null.

as aside, jcombobox listens comboboxmodel, don't have replace model; update in place.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -