代码之家  ›  专栏  ›  技术社区  ›  Stormshadow

如何在填充jcombobox时保持其弹出菜单打开?

  •  2
  • Stormshadow  · 技术社区  · 16 年前

    我的面板上有一个JCombobox。其中一个弹出菜单项是“更多”,当我单击它时,会获取更多菜单项并将它们添加到现有列表中。在此之后,我希望保持弹出菜单打开,以便用户意识到已经提取了更多项目,但是弹出菜单关闭。我使用的事件处理程序代码如下

    public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == myCombo) {
                JComboBox selectedBox = (JComboBox) e.getSource();
                String item = (String) selectedBox.getSelectedItem();
                if (item.toLowerCase().equals("more")) {
                    fetchItems(selectedBox);
                }
                selectedBox.showPopup();
                selectedBox.setPopupVisible(true);
            }
        }
    
    
    
    private void fetchItems(JComboBox box)
        {
            box.removeAllItems();
            /* code to fetch items and store them in the Set<String> items */
            for (String s : items) {
                box.addItem(s);
            }
        }
    

    我不明白为什么showPopup()和setPopupVisible()方法不能按预期工作。

    4 回复  |  直到 8 年前
        1
  •  4
  •   sreejith    16 年前

    在fetchitems方法中添加以下行

    SwingUtilities.invokeLater(new Runnable(){
    
        public void run()
        {
    
           box.showPopup();
        }
    

    }

    如果在Invokelater中调用selectedBox.showPopup();它也会工作。

        2
  •  1
  •   mfidan    12 年前

    覆盖jcombobox setpopupvisible metod

    public void setPopupVisible(boolean v) {
        if(v)
            super.setPopupVisible(v);
    }
    
        3
  •  0
  •   Rachid Chalouli    11 年前
    jComboBox1 = new javax.swing.JComboBox(){
    @Override
    public void setPopupVisible(boolean v) {
        super.setPopupVisible(true); //To change body of generated methods, choose Tools | Templates.
    }
    

    };

        4
  •  0
  •   mad_lobster    8 年前

    我找到了一些简单的方法来保持弹出窗口始终打开。它可能对一些定制的JComboBox很有用,就像我在项目中所使用的那样,但有一点黑客风格。

    public class MyComboBox extends JComboBox
    {
        boolean keep_open_flag = false; //when that flag ==true, popup will stay open
    
        public MyComboBox(){
            keep_open_flag = true; //set that flag where you need
            setRenderer(new MyComboBoxRenderer()); //our spesial render
        }
    
        class MyComboBoxRenderer extends BasicComboBoxRenderer {
    
            public Component getListCellRendererComponent(JList list, Object value, 
                int index, boolean isSelected, boolean cellHasFocus) {
    
                if (index == -1){ //if popup hidden
                    if (keep_open_flag) showPopup(); //show it again
                }
            }
        }
    }