简体   繁体   English

在多选JList中的特定项之间切换

[英]Toggling between specific items in a multi select JList

I have a class that extends JList & uses the DefaultListModel. 我有一个扩展JList并使用DefaultListModel的类。

So let's say that I have a list that contains items A, B, C, D, etc. 所以,假设我有一个包含项目A,B,C,D等的列表。

I am able to select multiple items, but I would like it so that A & B can never be selected at the same time. 我可以选择多个项目,但我希望它能够同时选择A&B。 So I would like it so that if I select A then B, A gets deselected selected and vice versa. 所以我希望如此,如果我选择A然后选择B,则选择A取消选择,反之亦然。

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. 您需要使用自定义ListSelectionModel并覆盖addSelectionInterval(...)方法。

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. 如果选择符合您的特定要求,则在调用super.addSelectionInterval(...)之前,此方法中的逻辑需要验证要选择的项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM