简体   繁体   中英

How do I find an item in a JList and set that as the selected value?

When I update the JList, I want to keep the selection of what it was before updating the JList. When updating a JList, it can either remove an object or add an object.

This is what I have right now:

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

But then sometimes, when an object is added or removed, it would throw an exception:

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)

That seems to me like a concurrency issue. Are you updating the selection index and removing/adding elements all on the Event Dispatch Thread (EDT), or are you running concurrent threads that do this? You should only change the selection or modify the list on the EDT.

I figured out what my problem was. peerList is a Vector, so before this I do the adding and deleting of elements from the Vector, not the JList, though I don't know if this is possible. So if I deleted an object from the Vector and I asked to get the selected value from a JList before updating it, it wouldn't be able to find it. But the JList would still show the deleted element until you use setListData and update the JList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM