0

我在这里寻找这个答案,但没有找到,所以如果有人需要,我会在下面写下我自己的答案。

如果需要,请随时更正任何内容。

4

1 回答 1

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;
    }
于 2012-11-03T11:22:33.307 回答