如果單擊JList上的選定索引,我希望它取消選擇。換句話說,點擊索引實際上會切換其選擇。不像這是支持的,所以我想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的MouseListeners,添加我自己的,然後添加所有默認偵聽器。這是行不通的,因爲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);
...和那個作品。但我不喜歡它。有沒有更好的辦法?
老實說,我會按照你已經描述的,使用'MouseAdapter'完成它。如果有更優雅的解決方案,我也很樂意聽到。 –
默認情況下,JList支持此功能,但您必須對所選項目進行Ctrl-點擊(至少在Windows上)才能取消選擇它。 – lbalazscs