Select multiple items in JList without using Ctrl / Command Key

I am looking for a way to select multiple items in a JList by simply clicking on each item.

The usual way to do this is to hold the / ctrl command key and then click.

I think it would be more intuitive to simply allow the user to enable and disable elements without having to hold an extra key.

+7
java user-interface swing
source share
4 answers

Think twice before changing the default behavior. Unless you have a special precedent, I would not want my list to work differently than everywhere :)

Having said that, you can use your own ListSelectionModel :

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

For this, you usually use the JCheckBox group.

Users are already in use with the fact that they need to press CTRL to select multiple items in the list. You should not change the default experience / expectation.

+4
source share
 list.setSelectionModel(new DefaultListSelectionModel() { private int i0 = -1; private int i1 = -1; public void setSelectionInterval(int index0, int index1) { if(i0 == index0 && i1 == index1){ if(getValueIsAdjusting()){ setValueIsAdjusting(false); setSelection(index0, index1); } }else{ i0 = index0; i1 = index1; setValueIsAdjusting(false); setSelection(index0, index1); } } private void setSelection(int index0, int index1){ if(super.isSelectedIndex(index0)) { super.removeSelectionInterval(index0, index1); }else { super.addSelectionInterval(index0, index1); } } }); 
+3
source share

I think you can easily do this by adding a mouse listener to your JList and programmatically selecting an element in the listener code. Of course, you probably need code to determine which item was clicked based on some coordinates.

0
source share

All Articles