如果点击JList上的选定索引,我希望它取消选择.换句话说,点击索引实际上会切换他们的选择.看起来不像这样被支持,所以我试过
list.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { java.awt.Point point = evt.getPoint(); int index = list.locationToIndex(point); if (list.isSelectedIndex(index)) list.removeSelectionInterval(index,index); } });
这里的问题是在JList已经对鼠标事件进行操作后被调用,所以它会取消选择所有内容.所以我试图删除所有的JList的MouseListener,添加自己的,然后添加所有的默认监听器.这没有工作,因为JList将在我取消选择之后重新选择索引.无论如何,我最终想到的是
MouseListener[] mls = list.getMouseListeners(); for (MouseListener ml : mls) list.removeMouseListener(ml); list.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { java.awt.Point point = evt.getPoint(); final int index = list.locationToIndex(point); if (list.isSelectedIndex(index)) SwingUtilities.invokeLater(new Runnable() { public void run() { list.removeSelectionInterval(index,index); } }); } }); for (MouseListener ml : mls) list.addMouseListener(ml);
…和那个工作.但我不喜欢有没有更好的办法?
解决方法
看一下示例“ListSelectionModel:启用切换选择模式”:
http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html
http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html
我已经对多选列表框进行了修改(将setSelectionInterval更改为addSelectionInterval),如果您在鼠标停止时单击以取消选择并移动鼠标,则可以消除重新选择的问题(移动手势启动检查以进行添加和去掉).
objList.setSelectionModel(new DefaultListSelectionModel() { private static final long serialVersionUID = 1L; boolean gestureStarted = false; @Override public void setSelectionInterval(int index0,int index1) { if(!gestureStarted){ if (isSelectedIndex(index0)) { super.removeSelectionInterval(index0,index1); } else { super.addSelectionInterval(index0,index1); } } gestureStarted = true; } @Override public void setValueIsAdjusting(boolean isAdjusting) { if (isAdjusting == false) { gestureStarted = false; } } });