【问题标题】:Flexible filtered list of data in combobox depending on another (previous) combobox selection组合框中的灵活过滤数据列表,取决于另一个(以前的)组合框选择
【发布时间】:2016-04-28 04:08:32
【问题描述】:

我有两个包含位置的组合框: 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 是 [],如输出所示。

【问题讨论】:

    标签: java combobox


    【解决方案1】:

    您真正需要的是当用户选择城市列表组合框时要调用的操作。您可以为该功能使用 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()方法在省份组合框中设置数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      相关资源
      最近更新 更多