[英]How to set an item as selected in JList
I would like to create a JButton
that when I press it it selects the last item of a JList
. 我想创建一个JButton
,当我按下它时,它将选择JList
的最后一项。
itemsList is my JList
, I already have some items on it itemsList是我的JList
,我已经有一些项目了
int selectedIndex = itemsList.getMaxSelectionIndex();
itemsList.setSelectedIndex(selectedIndex);
I tried this, but it doesn't select anything 我试过了,但是什么也没选
Your problem is that this method: getMaxSelectionIndex()
gets the max index of the current selections made in the JList (as per the JList API). 您的问题是此方法: getMaxSelectionIndex()
获取在JList中进行的当前选择的最大索引(根据JList API)。 This is not what it seems you want or need. 这似乎不是您想要或需要的。 Instead you need to get the size of the list, obtainable via the list's model, and remove 1 from it: 相反,您需要获取列表的大小(可通过列表的模型获得),并从中删除1:
itemsList.setSelectedIndex(itemsList.getModel().getSize() - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.