Java中使用ListSelectionListener时for循环无法正确获取用户选中项的问题
问题分析与解决
嘿,我一眼就揪出问题所在了!你在ListSelectionListener里构建输出字符串时,犯了个很容易忽略的小错误——循环里用了计数器i直接去取列表模型的元素,而非使用选中索引数组里的实际值。
错误根源
看看这段出问题的代码:
for(int i = 0; i < selectedIndices.length; i++) { output = output + (String)ctryJList.getModel().getElementAt(i) + " "; userSelected.setText(output); }
这里的i只是循环的计数变量,比如你选中了索引3(冰岛),selectedIndices.length是1,循环里i=0,所以你取的是模型里索引0的元素(美国),而非selectedIndices[0]对应的索引3的元素。这就是为什么选冰岛却显示美国,选其他项也只会按索引顺序展示,完全和实际选中内容不匹配。
修复方案
把循环里的i换成selectedIndices[i]就搞定了!这样就能根据选中的真实索引去获取对应的国家名称。另外还有个小优化:没必要每次循环都调用userSelected.setText(output),等整个字符串构建完成后再设置一次文本,性能更优。
修改后的valueChanged方法代码:
@Override public void valueChanged(ListSelectionEvent e){ // 避免选中过程中重复触发事件(比如拖动选中多项时会多次触发) if (e.getValueIsAdjusting()) { return; } int[] selectedIndices = ctryJList.getSelectedIndices(); String output = "Selected Items: "; for(int i = 0; i < selectedIndices.length; i++) { // 用选中索引数组里的值获取对应元素 output += (String)ctryJList.getModel().getElementAt(selectedIndices[i]) + " "; } // 循环结束后统一设置文本 userSelected.setText(output); System.out.println("Your countries are: " + output); }
额外小贴士
加上if (e.getValueIsAdjusting()) return;可以过滤掉选中过程中的中间触发事件,让你的逻辑只在选中操作完全结束后执行一次,更符合预期。
现在再运行试试,选冰岛就会正确显示冰岛,选多个项也能精准展示所有选中的国家啦!
内容的提问来源于stack exchange,提问作者CodedRoses
相关产品推荐
相关产品推荐

