vsr
vsr

Reputation: 45

Condition for JComboBox

I am using 2 JComboBoxes

String arr1[] = {"text1", "text2", "text3"};
String arr2[] = {"text1", "text2", "text3"};

JComboBox box1 = new JComboBox(arr1);
JComboBox box2 = new JComboBox(arr2);

where I am looking for conditions like

if(text1 in box1 is selected)
only text2 and text3 is selectable/enabled in box2

Upvotes: 0

Views: 715

Answers (3)

Alya'a Gamal
Alya'a Gamal

Reputation: 5638

If you want to Disable an item in your JComboBox without delete it , Like that :

enter image description here

So You can try this example

Upvotes: 0

Maroun
Maroun

Reputation: 95948

To get the selected value from the JComboBox you use getSelectedItem:

String value = (String)box.getSelectedItem();

Now you can check if value equals to text1, if so, you can use removeItem to remove items from the other JComboBox.

Upvotes: 1

Apurv
Apurv

Reputation: 3753

You can add an action listener to box1 and control what is shown/enabled in box2

box1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
             // code to manipulate values in box2 depending upon value in `box1Value`
            String box1Value = txtFilename.getSelectedItem().toString();
            if(box1Value.equalsIgnoreCase("text1")){
                String arr2[] = { "text2", "text3"};
                new JComboBox(arr2);
            } else {
                // ..
            }
        }
    });

Upvotes: 0

Related Questions