If I have a JTable which I attach a SelectionListener to because I want to
detect whenever a row changes, wither by mouse click or keyboard event, I
find that my SelectionListener is always picking up what the previous
selection was! The code below demonstrates this.
Obviously, I am missing something simple here. I am merely trying to pick up
what the newly selected row is. TIA - Ike
SelectionListener mySelectionListener = new SelectionListener(table);
table.getSelectionModel().addListSelectionListener(mySelectionListener);
table.getColumnModel().getSelectionModel().addListSelectionListener(mySelect
ionListener);
int selectedrow=-1;
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();
selectedrow =first;
} else if (e.getSource() ==
table.getColumnModel().getSelectionModel()
&& table.getColumnSelectionAllowed() ){
// Row selection changed
int first = e.getFirstIndex();
int last = e.getLastIndex();
selectedrow =first;
}
if (e.getValueIsAdjusting()) {
// The mouse button has not yet been released
return;
}
System.out.println(selectedrow);
}
}
Christian Kaufhold - 06 Apr 2005 16:10 GMT
> If I have a JTable which I attach a SelectionListener to because I want to
> detect whenever a row changes, wither by mouse click or keyboard event, I
[quoted text clipped - 26 lines]
> int last = e.getLastIndex();
> selectedrow =first;
What makes you think that the first row that changed was selected?
Christian
Ike - 06 Apr 2005 21:30 GMT
> What makes you think that the first row that changed was selected?
>
> Christian
SINGLE_SELECTION_MODEL, yes? -Ike
Morten Alver - 07 Apr 2005 07:42 GMT
> public void valueChanged(ListSelectionEvent e) {
> // If cell selection is enabled, both row and column change
[quoted text clipped - 5 lines]
> int last = e.getLastIndex();
> selectedrow =first;
The first and last indexes reported by the event encompass both selected
and unselected rows (all for which
selection status has changed). You can get the selected row by calling
"table.getSelectedRow()", which will give
you the correct value (at least when e.getValueIsAdjusting()==false).
--
Morten