首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ListSelectionListener错误索引

ListSelectionListener错误索引
EN

Stack Overflow用户
提问于 2015-05-08 10:01:01
回答 1查看 812关注 0票数 1

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

代码语言:javascript
复制
    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个元素时,选择last,然后单击first并输出为23 23。是关于事件的问题还是关于我的代码?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-08 10:10:38

你得到的行为是标准的行为,如果你想要有不同的行为,创建你自己的SelectionListener,同时考虑getValueIsAdjusting()

代码语言:javascript
复制
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);
    }
}

找到在这里解释这个例子

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30121037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档