简体   繁体   中英

Select Multiple Items In JList Without Using The Ctrl/Command Key

I am looking for a way to select multiple items within a JList by just clicking each item.

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

I think it would be more intuitive just to allow the user to click the items on and off without the need to hold an additional key.

Think twice before changing default behavior. Unless you have some special use-case, I'd not like my List to work different than everywhere else :)

Having said that, you should be able to 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);
        }
    }
});

For that you'd normally use a checkbox group of JCheckBox items.

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

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

I think you can easily accomplish this by attaching a mouse listener on your JList and selecting programatically the item in the listener code. Of course you will probably need some code to determine which item was pressed basing on some coordinates.

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