JTable: Remove border around cell when clearing row selection

qqilihq :

I have a JTable and want to allow deselecting all rows by clicking into an empty part of the table. This works fine so far. However, even though I call table.clearSelection(); the table still shows a border around the previously enabled cell (see cell 5 in the example):

Table deselection issue

I would like to get rid of this border as well (it looks especially out of place on the Mac's native look and feel, where the cells suddenly turn black).

Fully working minimal example code:

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 table.getColumnModel().getSelectionModel().clearSelection(); which was mentioned here around. But this does not help either.

camickr :

Tried to add table.getColumnModel().getSelectionModel().clearSelection();

The table.clearSelection() method invokes that method and the clearSelection() method of the TableColumnModel.

In addition to clearing the selection you also need to reset the "anchor and lead" indexes of the selection model:

table.clearSelection();

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

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

Now if you use the arrow keys the focus will go to (0, 0), so you do lose the information about the last cell that was clicked.

If you only clear the selection model, then you will lose the row information but the column information will remain.

Experiment with clearing one or both of the models to get the effect you desire.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466314&siteId=1