javaeclipseswingjlistlistselectionlistener

ListSelectionListener wrong index


I just wanted to see which element is getting selected, and change other labels and texfields on the frame as per the index. My code is as follows:

    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());
        }
    });

When I clicked first element output: 0 0 After clicking the second element: 1 1 After that I tried to click first element again, but this time output was 1 1 again. When I tried with 25 elements, selecting last element and after that click first element and output is 23 23. Is it about event's problem or it's about my code?


Solution

  • The behaviour you get is the standard one, if you want to have different one, create your own SelectionListener that considers also 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);
        }
    }
    

    Find here explanation of this example.