How do I open the JComboBox popup menu when full?

I have a JComboBox in my panel. One of the context menu items is More, and when I click the Me button, I get more menu items and add them to the existing list. After that I want the popup menu to be open so that the user understands that more items have been selected, the popup closes. The event handler code I am using is as follows

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);
        }
    }

      

I don't understand why the showPopup () and setPopupVisible () methods are not working as expected.

+2


a source to share


4 answers


add the following line to fetchItems method

SwingUtilities.invokeLater(new Runnable(){

    public void run()
    {

       box.showPopup();
    }

      



}

If u calls selectedBox.showPopup (); inside the invokelater and it will work.

+4


a source


overwrite JCombobox's setPopupVisible method



public void setPopupVisible(boolean v) {
    if(v)
        super.setPopupVisible(v);
}

      

+1


a source


jComboBox1 = new javax.swing.JComboBox(){
@Override
public void setPopupVisible(boolean v) {
    super.setPopupVisible(true); //To change body of generated methods, choose Tools | Templates.
}

      

};

0


a source


I found some simple solution to always keep the popup open. This can be useful with some custom JComboBoxes like the one I have in my project, but a little hacky.

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
            }
        }
    }
}

      

0


a source







All Articles