Trim
Trim

Reputation: 373

Java JComboBox resetting selection when setting the model

I have a JComboBox that is populated by values in a database. The values are checked constantly to update the list for the combobox. The values normally stay the same, but sometimes one may be removed or added. I have a method to update the list without notifying listeners that a change had been made to prevent the selection list popup from disappearing This is the method:

    public static void updateList(List curList, List items, JComboBox box,
        boolean addEmptyItem) {

    curList.clear();
    curList.addAll(items);

    ActionListener[] listeners = box.getActionListeners();
    for (ActionListener al : listeners) {
        box.removeActionListener(al);
    }

    Object selected = box.getSelectedItem();

    box.removeAllItems();
    if (addEmptyItem) {
        box.addItem("");
    }
    for (Object t : curList) {
        box.addItem(t);
    }

    if (selected != null) {
        box.setSelectedItem(selected);
    } else {
        if (box.getItemCount() > 0) {
            box.setSelectedIndex(0);    
        } // end if     
    }

    if (listeners != null) {
        for (ActionListener al : listeners) {
            box.addActionListener(al);
        }
    }
}

The window tracks the curList and the items are the new list.

The selected item keeps getting reset to what it was before the popup appeared on every update (this is okay, the selected item should remain the same). However, this is affecting what the user is hovering over. This is especially noticeable when the popup contains a scroll bar because if the user scrolled down, and the selected item was first in the list, the popup automatically scrolls to the top to "select" the first item in the list. The fact that the mouse hover is moving up there is the real problem.

Is there a way to prevent the hover from changing to what item is selected?

Upvotes: 0

Views: 610

Answers (1)

camickr
camickr

Reputation: 324098

This is especially noticeable when the popup contains a scroll bar because if the user scrolled down

    Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
    BasicComboPopup popup = (BasicComboPopup)child;
    JList list = (JList)popup.getList();
    Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
    JScrollPane scrollPane = (JScrollPane)c;

The above code allows you to access the scrollpane being used by the combo box popup.

So you can save the viewport position and then restore it after your processing:

Point p = scrollPane.getViewport().getViewPosition();
// do your processing to update the combo box model
scrollPane.getViewport().setViewPosition( p );

Note If the above doesn't work then try wrapping the setViewPosition() statement in a SwingUtilities.invokeLater(....).

Upvotes: 2

Related Questions