user1597002
user1597002

Reputation:

Dynamically update JComboBox (NullPointerException)

I'm trying to dynamically update a JComboBox in swing application and getting a 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 and apply new
  this.accountSelectModel = new DefaultComboBoxModel(al);
  this.accountSelect.setModel(this.accountSelectModel);
 }

 public void removeComboBoxItems() {
    //A call HERE here resorts in a null exception pointer ???
    this.accountSelectModel.removeAllElements();
   }

 }

Thanks for any feedback.

UPDATE

Figured out the problem. Initially I was very sure this wasn't the problem (sorry for not putting in this code).

I was initially adding listener via addActionListener (inside Accounts) to the 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 the actionPerformed method inside the Accounts.

this solved my issue...

UPDATE 2

However, I would prefer (as well as what others have recommended) I don't have to make entire Accounts class ActionListener.

So I went to original and found the problem was each call to this.accountSelectModel.removeAllElements triggered an action in the inner AccountSelectListener that was added to this.accountSelect.

The listener was meant to set the new combo box option, but since it wasn't called at the time a select change occurred (but on removeAllElements), the object source (item) was null which when passed threw the NPE.

Upvotes: 3

Views: 1722

Answers (1)

trashgod
trashgod

Reputation: 205785

Avoid calling public methods in the constructor. In particular, check whether you're calling removeComboBoxItems() from a listener that is added before the Accounts constructor finishes, as might happen if you fail to construct Swing GUI objects on the event dispatch thread. By default, the value of accountSelectModel is null.

As an aside, JComboBox listens to its ComboBoxModel, so you don't have to replace the model; just update it in place.

Upvotes: 1

Related Questions