![](/img/trans.png)
[英]Jlist is not getting updated when an action performed by selecting an item in Combobox
[英]Why Jlist is selecting index 0 even when the item is not present there
為什么即使列表項不存在,Jlist仍選擇索引0。
這是我創建的JList lst的代碼,並將其內容設置為向量vct,該向量vct由類people的對象組成,這些對象在被調用toString()時提供了people的詳細信息。
現在,當我運行此代碼時,當我按ctrl + F時會調用該代碼,並且如果在輸入對話框中輸入“ alfozen”,則無論我搜索索引0(1st item)是什么,它都會選擇1st,3rd,5th和7th。 )始終顯示為選中狀態,這是我在stackOverflow上遇到的第一個問題,請讓我知道是否需要提供有關該問題的更多信息。在此先感謝
這是代碼,
if ((ke.getKeyCode() == KeyEvent.VK_F) && ((ke.getModifiers() &
KeyEvent.CTRL_MASK) != 0))
{
int i=0,j=0;
lst.clearSelection();
lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
String s=JOptionPane.showInputDialog("Enter Name to search : ");
if(s==null)return;
String arg[]=new String[vct.size()];
int arr[]=new int[vct.size()];
for(people p : vct)
{
arg[i++]=p.toString();
}
for(j=0,i=0;j<arg.length;j++)
{
if(arg[j].contains(s))
{
arr[i++]=j;
}
}
lst.setSelectedIndices(arr);
lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
那是因為你告訴它。
循環之后,arr的前i
元素包含匹配的索引。 其余包含什么? 好吧,您從來沒有給他們分配任何東西,所以他們擁有默認的int
值0。
因此,如果您有5個元素,並且第二,第三和第五個元素匹配,則ar
包含ar
。
因此,當您調用lst.setSelectedIndices(arr);
,選擇元素1、2、4、0和0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.