Jcombobox中下拉菜单的值比较多,用户不方便寻找,因此将这些值分类属于不同parent,在Jcombobox中初始只显示几个parent然后点击parent后 属于该parent的child会展开,再点一下就缩回。就像tree一样不知我的描述是否准确分不够再加~~

解决方案 »

  1.   

    我觉得你说的这个像select二级联动的效果呢
      

  2.   


        public static void main(String[] args) throws Exception{
            Item parent1=new Item("类别1");
            parent1.add(new Item("    1-001"));
            parent1.add(new Item("    1-002"));
            parent1.add(new Item("    1-003"));
            Item parent2=new Item("类别2");
            parent2.add(new Item("    2-001"));
            parent2.add(new Item("    2-002"));
            parent2.add(new Item("    2-003"));
            
            JComboBox cb=new MyComboBox(new Object[]{parent1,parent2});        JFrame r = new JFrame("测试");
            r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            r.setSize(300,200);
            r.add(cb,BorderLayout.NORTH);
            r.setVisible(true);
        }
        
        static class Item{
         Item parent;
         String title;
         ArrayList<Item> subs;
        
         public Item(String title){
         this.title=title;
         }
        
         public String toString(){
         return title;
         }
        
         public void add(Item it){
         if(subs==null){
         subs=new ArrayList<Item>();
         }
         it.parent=this;
         subs.add(it);
         }
        }
        
        static class MyComboBox extends JComboBox{
         DefaultComboBoxModel model;
            public MyComboBox(Object[] os){
                super(os);
                model=(DefaultComboBoxModel)getModel();
            }
            public void setPopupVisible(boolean b){
             Item it=(Item)getSelectedItem();
             int index=getSelectedIndex();
             if(!b && it!=null && it.subs!=null){
             boolean find=false;
             for(int i=model.getSize();--i>=0;){
             Item t=(Item)model.getElementAt(i);
             if(t.parent==it){
             //收拢
             find=true;
             model.removeElementAt(i);
             }
             }
             if(!find){
             //展开
             ArrayList<Item> subs=it.subs;
             for(Item t:subs){
             index++;
             model.insertElementAt(t,index);
             }
             }
             return;
             }
                super.setPopupVisible(b);
            }
        }