views:

171

answers:

1

I have a JComboBox on my Panel. One of the popup menu items is 'More' and when I click that I fetch more menu items and add them to the existing list. After this, I wish to keep the popup menu open so that the user realizes that more items have been fetched however, 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 do not understand why the showPopup() and setPopupVisible() methods are not functioning as expected.

+2  A: 

add the following line in the fetchItems method

SwingUtilities.invokeLater(new Runnable(){

    public void run()
    {

       box.showPopup();
    }

}

If u call selectedBox.showPopup(); inside invokelater also it will work.

sreejith
Thanks .. it worked. I had to create a new inner class implementing the Runnable interface and passed the JComboBox instance to the constructor of the inner class because the box object in the run() would be out of scope within the fetchItems() function.
Stormshadow
@Stormshadow: no you didn't need to create an inner class; a much simpler solution is to declare box to be final: private void fetchItems(final JComboBox box). Then the code in this answer will work perfectly.
jfpoilpret