0

I'm trying to write a program which will take the input from one drop-down box, and use that to calculate the drop down box for another field, but I keep running into a problem. To make it work, I have to remove all items from on JComboBox, before refilling it, but this causes the program to throw an exception.

jbox1.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    autoCalc();

    String s = jbox1.getSelectedItem().toString();
     workS.set1(s);  
    jbox2.removeAllItems();
     for(int i = 0; i <= workS.jbox1.getSelectedItem; i++)
         {
         String temp = ("" + i);
         jbox2.addItem(temp);
         } 
        autoCalc();
     }
});


jbox2.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    autoCalc();      
    String s = jbox2.getSelectedItem().toString();
     workS.set2(s);  
        autoCalc();
     }
});

As far as I can tell, removing all items from jbox2 calls the jbox2 actionlistener, which realises that the field is empty and throws an exception. Does anyone have a way around this?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • In `jbox2`'s `actionPerformed` method, check to see if `s` is `null` or not. This occurs because when you remove all the elements from the combo box, the selected item is set to null, triggering the action event... – MadProgrammer Sep 03 '12 at 00:12
  • As an alternative, consider the approach shown [here](http://stackoverflow.com/a/3191882/230513). – trashgod Sep 03 '12 at 00:33
  • please show your actual code instead of snippets written on the fly (int i = 0; < getSelectedItem wouldn't compile), best as an SSCCE – kleopatra Sep 03 '12 at 06:57

1 Answers1

1

Keep a reference of the ActionListener added to jbox2. Before removing the items and filling with new list remove the ActionListener and readd after model is filled with new items.

StanislavL
  • 56,971
  • 9
  • 68
  • 98