JComboBox item listener

lina picture lina · May 6, 2012 · Viewed 7.5k times · Source

I have two combo boxes. The first contains some operator (+ , - ,* ,/) and the second one contains some value from 0 to 10. When user select (/) in first combo box I want the second one to show a value from 2 to 10 instead of 0 to 10.

I've tried this:

String[] operators = {"+","-" ,"*", "/"};

String[] number = {"0","1","3"....."10"};

divisionModel= new DefaultComboBoxModel(new String[]{"2","3","4","5".."10"});



    operatorCombo = new JComboBox(operators);

    numberCombo = new JComboBox(number);


operatorCombo.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {


    if (operatorCombo .getSelectedItem().equals("/")){

        numberCombo .setModel(divisionModel);
  }

my problem is when I select ("/") the numberCombo works fine and show me numbers from 2 to 10 but when I click on another operator it still show me the numbers from 2 to 10 instead 0 to 10.How can I solve this problem?! Thanks

Answer

Andrew Thompson picture Andrew Thompson · May 6, 2012
// always compare objects using equals()
if (operatorCombo.getSelectedItem().equals("/")) {..

As to updating the 2nd combo, create a new model for it and call setModel(ComboBoxModel).