Search code examples
javaswingjlist

Make JList behave on click the same way as on ctrl+click?


I'm looking for a way to make a JList always toggle the selection for the clicked item without deselecting the others, the same way as ctrl click works.

The ListSelectionModel seems to be the right way to go but I can't figure out what has to be configured in there.

How to make a JList behave on click the same way as on ctrl click?


Solution

  • you have to make your own ListSelectionModel. try it.

    list.setSelectionModel(new DefaultListSelectionModel() 
    {
        @Override
        public void setSelectionInterval(int index0, int index1) 
        {
            if(list.isSelectedIndex(index0)) 
            {
                list.removeSelectionInterval(index0, index1);
            }
            else 
            {
                list.addSelectionInterval(index0, index1);
            }
        }
    });