views:

1965

answers:

2

I've implemented my own event handler and added it to the selection model of the table:

table.getSelectionModel().addListSelectionListener(event);

And implemented the method for "event" (mentioned above):

public void valueChanged(ListSelectionEvent e) {
    log.debug("value changed");
}

Unfortunately the event fires twice if I chance the selection and it doesn't seem possible to find the associated table, because e.getSource provides javax.swing.DefaultListSelectionModel.

Hence my questions are:

1) Why does it fire twice although the eventListener is only registered once?

2) How can I find the table for which the selection applies? The DefaultListSelectionModel doesn't seem to offer any getSource() or similar.

Many thanks!

+2  A: 

1) I think you'll find it fires once for de-selecting the old selection and once for selecting the new selection. If you log the details of the event you should see exactly what's going on. I can't remember the details, so perhaps this is wrong. Either way you should be able to call getValueIsAdjusting() on the event and only use the last one in the chain (ie when it returns false).

2) You shouldn't normally need to, but AFAIK the only way to do this is to create your Listener specifically for the table (ie pass the table to the constructor and remember it).

Draemon
Thank you very much, that was exactly what I was looking for! getValueIsAdjusting() should be false as you wrote.
MrG
+2  A: 

Since more than one JTable (or other component I'm guessing) can share the same selection model, it doesn't make sense to ask for the associated JTable from the event. This is the same reason that you can't retrieve a JTable from a TableModel. As Draemon suggests, store the reference to the JTable in (or make it accessible to) your listener class.

Dave Ray