简体   繁体   中英

JList actionlistener “delay” in selecting item

I have a JList populated by what is initially an ArrayList<SomeClass> which I convert to an array. This JList is then wrapped in a JScrollPane and displayed on a JFrame . When I select an item in it, the first item selected is correct, but after that it seems to select the previous item. So if I have an ArrayList<String> populated "Number 0", "Number 1", "Number 2", etc. and I select 19, 18, 17 in that order, the output is as if I'd selected 19, 19, 18:

import java.awt.Dimension;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;

public class DemoFrame extends JFrame implements ListSelectionListener{
    ArrayList<String> strings;
    public DemoFrame(){
        strings = new ArrayList();
        for (int i=0; i<20; i++){
            strings.add("Number " + i);
        }
        JList demoList = new JList();
        demoList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        demoList.setVisibleRowCount(10);
        JScrollPane listScroller = new JScrollPane(demoList);
        listScroller.setPreferredSize(new Dimension(250, 500)); 
        demoList.setListData(strings.toArray());
        this.add(listScroller);
        demoList.addListSelectionListener(this);
        getContentPane().add(listScroller);
        pack();
        setVisible(true);
    }

    @Override
    public void valueChanged(ListSelectionEvent lse) {
        if (!lse.getValueIsAdjusting()){
            System.out.println(lse.getLastIndex());
            System.out.println(strings.get(lse.getLastIndex()));
        }
    }
}

public class SODemo{
    public static void main(String[] args) {
        DemoFrame demo = new DemoFrame();
    }
}

Output from selecting 19, 18. 17:

run: 19 Number 19 19 Number 19 18 Number 18

However, Output from selecting 0, 1, 2:

run: 0 Number 0 1 Number 1 2 Number 2

Why is it behaving like this?

There are 2 methods of interest in the ListSelectionEvent class:

public int getFirstIndex()

Returns the index of the first row whose selection may have changed.

public int getLastIndex()

Returns the index of the last row whose selection may have changed.

So a selection event actually involves 2 list elements, the one gaining focus and the one losing focus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM