JTable: remove border around cell when clearing row selection

I have JTableand you want to allow deselecting all rows by clicking in the empty part of the table. So far this is wonderful. However, although I call table.clearSelection();, the table still shows the border around the previously activated cell (see Cell 5 in the example):

Table deselection issue

I would also like to get rid of this border (this looks especially out of place on Mac's own appearance, where cells suddenly turn black).

A fully working minimal code example:

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] Tried to add the table.getColumnModel().getSelectionModel().clearSelection();one mentioned here. But that doesn't help either.

+6
source share
2 answers

table.getColumnModel(). getSelectionModel(). clearSelection();

table.clearSelection() clearSelection() TableColumnModel.

reset " " :

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), .

, , .

, .

+3

: , , , . , , . :

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

Source: https://habr.com/ru/post/1016573/


All Articles