简体   繁体   中英

Toggling between specific items in a multi select JList

I have a class that extends JList & uses the DefaultListModel.

So let's say that I have a list that contains items A, B, C, D, etc.

I am able to select multiple items, but I would like it so that A & B can never be selected at the same time. So I would like it so that if I select A then B, A gets deselected selected and vice versa.

Is this possible?

Edit: Added initial implementation

public TestList extends JList {
    public void TestList() {
        super(new DefaultModelList());
    }

    // Method 2
    public void addSelectionInterval(int anchor, int lead) {
        //DO Work
    }

    // Method 3
    public void setSelectedValue(Object obj, boolean shouldScroll) {
        // DO WORK
    }
}

TestList test = new TestList();
// Method 1
test.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
        // check value selected and deselect if necessary
    }
}

I have tried these ways, but none of them seem to be working. The current issue is when I select an item, none of these get run as far as I can tell.

You would need to use a custom ListSelectionModel and override the addSelectionInterval(...) method.

The logic in this method would need to validate the item about to be selected, before you invoke super.addSelectionInterval(...) if the selection meets your specific requirement.

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