Reputation: 1219
I am using a JTable. I need to get a notification whenever a cell selection change. I tried to use the ListSelectionListener but I only get notification when the row selection change. If I select a new column on the same row, I don't get notify. I need to know when the cell is selected, not when the cell is changed. Is there a listener that I can use to do this ?
Upvotes: 12
Views: 22579
Reputation: 51536
One way to receive notification on column selection changes - as already answered by @parsifal(in the comments - is to grab the TableColumnModel's internal selectionModel and register a listener:
table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener);
Another way is to register a TableColumnModelListener with the columnModel:
table.getColumnModel().addColumnModelListener(columnModelListener);
The first is "shorter" in terms of code: just one method to implement vs. several - most empty except the columnSelectionChanged.
The second is more robust against dynamic changes: with the first there is no possibility to guard against changes of the selectionModel property of the columnModel ... because it is not a property. Or in other words: in the (concededly rare) case that application code swaps out the selectionModel the listener is listening to the Void. Installing a columnModelListener is immune against such a change, as the columnModel passes on the events from its selectionModel whichever it would be.
Upvotes: 5
Reputation: 266
The easiest way to do this is to call setCellSelectionEnabled(true)
, and pass a reference to your table to the listener. When the listener is invoked, call getSelectedRow()
and getSelectedColumn()
on the original table.
The alternative is to set a row selection listener on the table, a column selection listener on the ColumnModel
, and then figure out their intersection.
Upvotes: 11