灵活的组合框中的数据过滤列表取决于另一个(先前的)组合框选择

时间:2016-04-28 04:08:32

标签: java combobox

我有两个包含位置的组合框: 1st combobox lists the cities. 2nd combobox lists the pronvices in the city. So the values that should be listed in the 2nd combobox is dependent on the 1st combobox.

我从mysql数据库中获取值。这是我的代码:

locList1 = new ArrayList<Locations_Master>();  
    locList1 = locDAO.getLM(); //contains the list of all Cities and Barangays from database

    cityS1 = "";
    citySL1 = new LinkedHashSet<String>();
    for(int i = 0; i<locList1.size(); i++){
        cityS1 = locList1.get(i).getCity() + "\n";
        citySL1.add(cityS1);
    }
    cityList1 = new JComboBox(citySL1.toArray());
    cityList1.setBounds(5, 110, 170, 20);
    mainPanel.add(cityList1);
    cityList1.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent e){
            selectedCity = cityList1.getSelectedItem().toString();
            mainPanel.validate();
            mainPanel.repaint();

        }
    });
    barSL1 = new LinkedHashSet<String>();
    for(int i=0; i<locList1.size(); i++){ 
        if(locList1.get(i).getCity().equals(selectedCity)){
            barS1 = locList1.get(i).getBarangay()+"\n";
            barSL1.add(barS1); 
        //I tried filtering the barangay values here dependent on the selected city

        }
        System.out.println(barSL1);
    }
    barList1 = new JComboBox(barSL1.toArray());
    barList1.setBounds(185, 110, 170, 20);
    mainPanel.add(barList1);

每次用户选择一个城市时,都应该显示城市下面列出的城镇。输出中没有“错误”,但barSL1是[],如输出中所示。

1 个答案:

答案 0 :(得分:0)

您实际需要的是当用户选择citylist comboBox时要调用的操作。您可以为该函数使用addPopupMenuListener接口。 因此,每当用户点击组合框的弹出菜单中的项目时,将调用事件。通过在cityList组合中输出所选值,您可以调整省组合框。

 cityList1.addPopupMenuListener(new actionCombo());

 class actionCombo implements PopupMenuListener{

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {

        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
         String cityname = combo1.getSelectedItem().toString();
            adjustProvince(cityname);
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {

        }

  } 

 public void adjustProvince(String cityName){
 province.addItem(cityName);
 }

您可以完成adjustProvince()方法在省组合框中设置数据。