shashank
shashank

Reputation: 11

Deselect rows of JTable

I have 7 tables on my screen. Since they are independent tables, I'am able to select a cell from each one of them.

Although I want that every time I make a selection of a cell in a table, I want a deselection of cell from the table from which cell was previously selected and so one for other tables as well.

Basically I want selection of a cell from a single table at a time.

Also I would want deselection of the selected cell whenever mouse is clicked anywhere on the screen.

I've tried clearselection(), but it doesn't seem to work.

Upvotes: 0

Views: 951

Answers (1)

trashgod
trashgod

Reputation: 205875

Create a TableGroup to enforce SINGLE_SELECTION across a group of tables, each having its own ListSelectionModel. The example below contains a List<JTable> that can manage the selection for an arbitrary number of tables.

Usage:

SelectionGroup group = new SelectionGroup();
group.add(new JTable(…));
group.add(new JTable(…));
…

Code:

private static class TableGroup {

    private final List<JTable> list = new ArrayList<>();

    private void add(JTable table) {
        list.add(table);
        ListSelectionModel model = table.getSelectionModel();
        model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        model.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    for (JTable t : list) {
                        if (!t.equals(table)) {
                            t.clearSelection();
                        }
                    }
                }
            }
        });
    }
}

TableGroup is conceptually similar to a ButtonGroup, seen here and here.

Upvotes: 1

Related Questions