gpt4 book ai didi

java - ListSelectionListener 索引错误

转载 作者:行者123 更新时间:2023-11-29 05:06:48 27 4
gpt4 key购买 nike

我只是想看看哪个元素被选中,并根据索引更改框架上的其他标签和文本域。我的代码如下:

    list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);

list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
System.out.println(e.getLastIndex());
}
});

当我点击第一个元素输出时:0 0点击第二个元素后:1 1之后我再次尝试点击第一个元素,但这次输出又是 1 1。当我尝试使用 25 个元素时,选择最后一个元素,然后单击第一个元素,输出为 23 23。是关于事件的问题还是关于我的代码?

最佳答案

您获得的行为是标准行为,如果您想要不同的行为,请创建您自己的 SelectionListener 并同时考虑 getValueIsAdjusting() .

class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();

int firstIndex = e.getFirstIndex();
int lastIndex = e.getLastIndex();
boolean isAdjusting = e.getValueIsAdjusting();
output.append("Event for indexes "
+ firstIndex + " - " + lastIndex
+ "; isAdjusting is " + isAdjusting
+ "; selected indexes:");

if (lsm.isSelectionEmpty()) {
output.append(" <none>");
} else {
// Find out which indexes are selected.
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for (int i = minIndex; i <= maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
output.append(" " + i);
}
}
}
output.append(newline);
}
}

查找here explanation of this example .

关于java - ListSelectionListener 索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121037/

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