Listening for Selection Events in a JTable Component

To listen for selection changes, you need to add a listener to both the JTable's table model and to the table column model.

A selection change event has a first and last property that specifies the range of affected rows (or columns). For example, if the 5th row is selected and the user selects the 7th row, the first property is 4 and the last is property 6. There is not enough information in the event to determine exactly which cells have changed. See Getting the Selected Cells in a JTable Component for an example of how to determine the selected cells.

Changing the selection programmatically (see Programmatically Making Selections in a JTable Component) causes selection change events to be fired.

SelectionListener listener = new SelectionListener(table); table.getSelectionModel().addListSelectionListener(listener); table.getColumnModel().getSelectionModel() .addListSelectionListener(listener); public class SelectionListener implements ListSelectionListener { JTable table; // It is necessary to keep the table since it is not possible // to determine the table from the event's source SelectionListener(JTable table) { this.table = table; } public void valueChanged(ListSelectionEvent e) { // If cell selection is enabled, both row and column change events are fired if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) { // Column selection changed int first = e.getFirstIndex(); int last = e.getLastIndex(); } else if (e.getSource() == table.getColumnModel().getSelectionModel() && table.getColumnSelectionAllowed() ){ // Row selection changed int first = e.getFirstIndex(); int last = e.getLastIndex(); } if (e.getValueIsAdjusting()) { // The mouse button has not yet been released } } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.