JList - 单击已选择的项目时取消选择 [英] JList - deselect when clicking an already selected item
问题描述
如果单击JList上的选定索引,我希望它取消选择。换句话说,点击索引实际上会切换他们的选择。看起来不支持,所以我尝试了
If a selected index on a JList is clicked, I want it to de-select. In other words, clicking on the indices actually toggles their selection. Didn't look like this was supported, so I tried
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的MouseListeners,添加我自己的,然后添加所有默认侦听器。这不起作用,因为在我取消选择后,JList会重新选择索引。无论如何,我最终提出的是
The problem here is that this is being invoked after JList has already acted on the mouse event, so it deselects everything. So then I tried removing all of JList's MouseListeners, adding my own, and then adding all of the default listeners back. That didn't work, since JList would reselect the index after I had deselected it. Anyway, what I eventually came up with is
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);
......这是有效的。但我不喜欢它。有更好的方法吗?
... and that works. But I don't like it. Is there a better way?
推荐答案
在此处查看示例ListSelectionModel:启用切换选择模式:
< a href =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
Looking at the Example "ListSelectionModel: Enabling Toggle Selection Mode" here: http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html
我已经为多选列表框略微修改了它(将setSelectionInterval更改为addSelectionInterval)并且如果你点击到它就消除了重新选择的问题在鼠标停止时取消选择并移动鼠标(移动gestureStarted检查添加和删除)。
I have modified it slightly for multi-select list boxes (changed setSelectionInterval to addSelectionInterval) and eliminated a problem with re-selection if you click to de-select and move your mouse while the mouse is down (moved the gestureStarted check for both add and remove).
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;
}
}
});
这篇关于JList - 单击已选择的项目时取消选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!