如何在JList中找到项目并将其设置为选定值?

时间:2012-12-14 07:51:19

标签: java swing jlist

当我更新JList时,我想在更新JList之前保留选择它的内容。更新JList时,它可以删除对象或添加对象。

这就是我现在所拥有的:

Object obj = list.getSelectedValue(); // This is line 47
list.clearSelection();
list.setListData(peerList);

if(obj != null)
{
   int selectedIndex = list.getNextMatch(obj.toString(), 0, Position.Bias.Forward);

   if(selectedIndex != -1)
      list.setSelectedIndex(selectedIndex);
   else
      list.clearSelection();
}

但有时,当添加或删除某个对象时,它会引发异常:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 3
    at java.util.Vector.elementAt(Unknown Source)
    at javax.swing.JList$5.getElementAt(Unknown Source)
    at javax.swing.JList.getSelectedValue(Unknown Source)
    at MyThread$1.run(MyThread.java:47) // I marked up top where line 47 is
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

2 个答案:

答案 0 :(得分:3)

在我看来,这似乎是一个并发问题。您是否在事件调度线程(EDT)上更新选择索引并删除/添加元素,或者您是否正在运行执行此操作的并发线程?您只应更改选择或修改EDT上的列表。

答案 1 :(得分:1)

我弄清楚我的问题是什么。 peerList是一个Vector,所以在此之前我从Vector中添加和删除元素,而不是JList,尽管我不知道这是否可行。因此,如果我从Vector中删除了一个对象,并且在更新它之前我要求从JList中获取所选值,它将无法找到它。但是在您使用setListData并更新JList之前,JList仍会显示已删除的元素。