gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:39:24 24 4
gpt4 key购买 nike

当我更新 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)

最佳答案

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

关于java - 如何在 JList 中找到一个项目并将其设置为选定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13874657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com