0

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
lina
  • 75
  • 2
  • 4
  • 10
  • 2
    !) There is no `ComboBox` in Swing. Did you mean `JComboBox`? If so, copy/paste the name. If not, don't mix Swing & AWT Components. 2) [What have you tried?](http://www.whathaveyoutried.com/) I mean *besides* asking random strangers on the internet to do it for you. – Andrew Thompson May 06 '12 at 18:30
  • divisionModel = new DefaultComboBoxModel(new String[]{"2","3"....}); if (operatorCombo.getSelectedItem()== "/"){ operatorCombo.setModel(divisionModel ); – lina May 06 '12 at 19:13
  • this code is work when I select (/) but I dont know what should to do when I re-select another item for example + because it is not showing all items another time just from 2 to 10 – lina May 06 '12 at 19:21

2 Answers2

2
// 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).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • yes I did that and work fine when I select (/) but my problem is when I select another operator like + ,secondCombo suppose to show all number from 0 to 10 but it just show from 2 to 10 – lina May 06 '12 at 19:31
  • I did not recommend you post *"the code"*, I recommended you post ***an SSCCE.*** Follow the link, read the document. – Andrew Thompson May 06 '12 at 20:49
2

You might look at this example that shows how the selection made in one JComboBox can change the appearance of related JComboBox by using a different DefaultComboBoxModel.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045