JTable:清除行选择时删除单元格周围的边框

qqi*_*ihq 6 java swing jtable

我有一个JTable并希望通过单击表格的空白部分来取消选择所有行.这到目前为止工作正常.但是,即使我调用table.clearSelection();该表仍然显示以前启用的单元格周围的边框(请参阅示例中的单元格5):

表取消选择问题

我也希望摆脱这个边界(它看起来特别不合适Mac的原生外观和感觉,细胞突然变黑).

完全工作的最小示例代码:

public class JTableDeselect extends JFrame {
    public JTableDeselect() {
        Object rowData[][] = { { "1", "2", "3" }, { "4", "5", "6" } };
        Object columnNames[] = { "One", "Two", "Three" };
        JTable table = new JTable(rowData, columnNames);
        table.setFillsViewportHeight(true);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (table.rowAtPoint(e.getPoint()) == -1) {
                    table.clearSelection();
                }
            }
        });
        add(new JScrollPane(table));
        setSize(300, 150);
    }
    public static void main(String args[]) throws Exception {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        new JTableDeselect().setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

[编辑]试图添加table.getColumnModel().getSelectionModel().clearSelection();这里提到的.但这也无济于事.

Hov*_*els 5

你的问题:即使选择丢失,你的表格单元仍然具有焦点,因此它通过显示加厚的边框来显示它.知道一种可能的解决方案是创建自己的渲染器,在单元格失去选择时移除单元格的焦点.例如:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (!isSelected) {
            hasFocus = false;
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
});
Run Code Online (Sandbox Code Playgroud)


cam*_*ckr 3

尝试添加 table.getColumnModel().getSelectionModel().clearSelection();

table.clearSelection()方法调用该方法和clearSelection()的方法TableColumnModel

除了清除选择之外,您还需要重置选择模型的“锚点和引导”索引:

table.clearSelection();

ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setAnchorSelectionIndex(-1);
selectionModel.setLeadSelectionIndex(-1);

TableColumnModel columnModel = table.getColumnModel();
columnModel.getSelectionModel().setAnchorSelectionIndex(-1);
columnModel.getSelectionModel().setLeadSelectionIndex(-1);
Run Code Online (Sandbox Code Playgroud)

现在,如果您使用箭头键,焦点将转到 (0, 0),因此您确实会丢失有关单击的最后一个单元格的信息。

如果只清除选择模型,那么您将丢失行信息,但列信息将保留。

尝试清除一个或两个模型以获得您想要的效果。