我在这里寻找这个答案,但没找到,所以如果有人需要,我会在下面写下自己的答案。
如果需要,请随时更正。
答案 0 :(得分:0)
因此,为了为这两种情况(JList和JTable)提供解决方案,我创建了一个自定义侦听器,该侦听器将应用于相关的列表和表。
听众是:
public class DeselectOnClickListener extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
clearselection(e);
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
clearselection(e);
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
clearselection(e);
}
public void clearselection (MouseEvent e){
if (e.getComponent() instanceof JTable){
Point pClicked = e.getPoint();
JTable table = (JTable) e.getSource();
int index = table.rowAtPoint(pClicked);
if (index == -1){
table.clearSelection();
}
} else if (e.getComponent() instanceof JList){
Point pClicked = e.getPoint();
JList<?> list = (JList<?>) e.getSource();
int index = list.locationToIndex(pClicked);
Rectangle rec = list.getCellBounds(index, index);
if (rec==null || !rec.contains(pClicked)){
list.clearSelection();
}
}
}
}
请注意,这在SINGLE_SELECCTION
中运行良好,但如果我们要使用MULTIPLE_INTERVAL_SELECTION
或SINGLE_INTERVAL_SELECTION
,我建议不要覆盖mouseReleased(MouseEvent e)
,因为如果鼠标按钮在选择范围之外释放。
PD:对于最后一点,我做了以下修复:
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
if (! isIntervalSelectionMode(e)){
clearselection(e);
}
}
public boolean isIntervalSelectionMode (MouseEvent e){
boolean isIntervalSelection = false;
if (e.getComponent() instanceof JTable){
isIntervalSelection = ((JTable)e.getSource()).getSelectionModel().getSelectionMode()
!= ListSelectionModel.SINGLE_SELECTION;
}else if (e.getComponent() instanceof JList){
isIntervalSelection = ((JList<?>)e.getSource()).getSelectionModel().getSelectionMode()
!= ListSelectionModel.SINGLE_SELECTION;
}
return isIntervalSelection;
}