在不使用Ctrl / Command键的情况下在JList中选择多个项目

我正在寻找一种方法来通过单击每个项目来选择JList中的多个项目。

执行此操作的常规方法是按住命令/ ctrl键,然后单击。

我认为只需允许用户点击和关闭项目而无需持有其他密钥就更直观了。

在更改默认行为之前请三思。 除非你有一些特殊的用例,否则我不喜欢我的List工作与其他地方不同:)

话虽如此,您应该能够使用自己的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); } } }); 

为此,您通常使用JCheckBox项目的复选框组。

用户已经习惯使用CTRL来选择列表框中的多个项目。 您不应该更改默认体验/期望。

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

我认为您可以通过在JList上附加鼠标侦听器并以编程方式选择侦听器代码中的项目来轻松实现此目的。 当然,您可能需要一些代码来确定基于某些坐标按下了哪个项目。