ListSelectionListener 索引错误

ListSelectionListener wrong index

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

    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.