如何使用 setSelectedValue 在 JList 中设置多个项目?
我有一个 jList,它是通过添加到底层 listModel 来动态填充的。现在,如果我有三个字符串,其值我知道并且我
for(i=0;i<3;i++){
jList.setSelectedValue(obj[i],true);//true is for shouldScroll or not
}
只选择了最后一项...如果无法完成此操作并且我必须从基础模型中设置选择,我应该如何处理? ?
另请注意 jList 有选择模式:
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
提前致谢
I have a jList that is populated dynamically by adding to the underlying listModel. Now if I have three Strings whose value I know and I do
for(i=0;i<3;i++){
jList.setSelectedValue(obj[i],true);//true is for shouldScroll or not
}
only the last item appears to be selected...If this can't be done and I have to set the selection from the underlying model how should I go about it???
Also please note the jList has selection mode:
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Thanks in Advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,所有 xxSelectedValue 方法都是 JList 上的 SelectionModel(仅支持基于索引的选择访问)的便捷包装方法。不支持为每个值设置多个选择。如果你真的想要它,你必须自己实现一个方便的方法。基本上,您必须循环模型的元素,直到找到相应的索引并调用基于索引的方法,例如:
Note that all xxSelectedValue methods are convenience wrapper methods around the selectionModel (which supports index-based selection access only) on the JList. Setting multiple selections per value is not supported. If you really want it, you'll have to implement a convenience method yourself. Basically, you'll have to loop over the model's elements until you find the corresponding indices and call the index-based methods, something like:
虽然StanislasV回答 完全有效,我宁愿避免将一个选择间隔添加到另一个选择间隔。相反,您应该更喜欢调用关联的
JList
ListSelectionModel#setSelectionInterval(int, int)
方法如下:如果您想要列表选择是不相交的,您还必须编写自己的
ListSelectionModel
。Although StanislasV answer is perfectly valid, i would prefer to avoid adding one selection interval to another. Instead, you should prefer to call the
JList
associatedListSelectionModel#setSelectionInterval(int, int)
method like this :If you want your list selection to be disjoint, you'll moreover have to write your own
ListSelectionModel
.