2016-08-23 70 views
0

我有一个JComboBox由数据库中的值填充。值不断检查以更新组合框的列表。值通常保持不变,但有时可能会被删除或添加。我有没有通知已进行了更改,这样来避免选择列表弹出窗口消失这是该方法的听众来更新列表的方法:Java JComboBox重置设置模型时的选择

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

窗口跟踪curListitems是新的列表。

所选项目不断重置为弹出窗口出现在每次更新之前的状态(这没关系,所选项目应该保持不变)。但是,这影响了用户的悬停。这在弹出窗口包含滚动条时尤为明显,因为如果用户向下滚动,并且所选项目首先位于列表中,则弹出窗口会自动滚动到顶部以“选择”列表中的第一项。鼠标悬停在那里的事实是真正的问题。

有没有办法来防止悬停改变到选择的项目?

+1

考虑动态删除/添加JComboBox的ItemListener – copeg

+0

@copeg我删除/添加了ItemListeners,就像您提到ActionListeners被删除的方式,这解决了我所看到的问题。谢谢! – Trim

回答

2

这是尤其明显,当弹出包含一个滚动条,因为如果用户向下滚动

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; 

上面的代码可以访问滚动窗格正在使用组合框弹出。

所以,你可以保存视口的位置,然后你的处理后,将其恢复:

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

注意如果以上不工作,然后尝试在SwingUtilities.invokeLater(....)包裹setViewPosition()声明。