3

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.

4

1 回答 1

1

避免在构造函数中调用公共方法。特别是,检查您是否removeComboBoxItems()从在构造函数完成之前添加的侦听器调用Accounts,如果您未能在事件调度线程上构造 Swing GUI 对象,可能会发生这种情况。默认情况下, 的accountSelectModel值为null

顺便说一句,JComboBox听它的ComboBoxModel,所以你不必更换模型;只需将其更新到位。

于 2013-05-04T20:49:45.363 回答