繁体   English   中英

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

[英]JTable: Remove border around cell when clearing row selection

我有一个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);
    }
}

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

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

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);
    }
});

试图添加table.getColumnModel()。getSelectionModel()。clearSelection();

table.clearSelection()方法调用该方法和TableColumnModelclearSelection()方法。

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

table.clearSelection();

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

TableColumnModel columnModel = table.getColumnModel();
columnModel.getSelectionModel().setAnchorSelectionIndex(-1);
columnModel.getSelectionModel().setLeadSelectionIndex(-1);

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

如果仅清除选择模型,则将丢失行信息,但列信息将保留。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM