Dynamic JComboBoxes

后端 未结 2 1119
天命终不由人
天命终不由人 2020-11-22 04:27

I have following data (String):

Course1: A1
Course1: A2
Course2: B1
Course2: B2
Course2: B3
Course2: B4
Course3: C1
Course3: C2

I\'d like t

2条回答
  •  名媛妹妹
    2020-11-22 04:49

    Yes. You can add a change event listener to the first JComboBox that updates the values of the second JComboBox.

    Something like this

    // first comboBox
    final JComboBox courseBox = new JComboBox(
                                   new String[]{"Course 1", "Course 2", "Course 3"});
    
    final JComboBox box2 = new JComboBox();
    
    // Now listen for changes
    courseBox.addActionListener(new ActionListener(){
       void actionPerformed(ActionEvent e){
           if(courseBox.getSelectedItem().equals("Course 1")){
               // we know that the user picked "Course 1", now change box2 to match
               // first clear everything
               box2.removeAllItems();
               // now add back relevant values
               box2.addItem("A1");
               box2.addItem("A2");
           }else if(...){
               // ...
           }
       }
    });
    

提交回复
热议问题