java 在不使用 Ctrl/Command 键的情况下选择 JList 中的多个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2404546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select Multiple Items In JList Without Using The Ctrl/Command Key
提问by Gordon
I am looking for a way to select multiple items within a JList by just clicking each item.
我正在寻找一种方法,只需单击每个项目即可在 JList 中选择多个项目。
The normal way to do this is to hold the command/ctrl key and then click.
执行此操作的正常方法是按住 command/ctrl 键,然后单击。
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.
我认为仅允许用户打开和关闭项目而无需按住额外的键会更直观。
回答by Peter Lang
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 :)
在更改默认行为之前要三思。除非你有一些特殊的用例,否则我不希望我的 List 与其他地方不同:)
Having said that, you should be able to use your own ListSelectionModel:
话虽如此,您应该能够使用自己的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);
}
}
});
回答by BalusC
回答by Francisco
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);
}
}
});
回答by pajton
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.
我认为您可以通过在 JList 上附加一个鼠标侦听器并以编程方式选择侦听器代码中的项目来轻松完成此操作。当然,您可能需要一些代码来根据某些坐标确定按下了哪个项目。

