Swing: listeners execution order on custom component
Question
My custom component is composed of three JTree
s inside a JPanel
. Only one JTree
should be selected at a time, so I've added a TreeSelectionListener
to each of them that calls clearSelection
on the previously selected JTree
.
I'd like to add other TreeSelectionListener
s to the JTree
s being sure that the selection- handling listeners always get executed first. I'd prefer not to put everything in one single TreeSelectionListener
.
What should I do? Thanks in advance!
Solution
Probably you could chain them by adding the new listener to the existing one in such a way the next time your listener gets invoked it in turn will forward the event to its listeners.
// This is your current listener implementation
class CustomTreeSelectionListener implements TreeSelectionListener {
// listeners to which the even will be forwarded
private List<TreeSelectionListener> ownLIsteners;
public void addListener( TreeSelectionListener newListener ) {
ownListeners.add( newListener );
}
// add also removeListener( .... )
// TreeSelectionListener interface implementation...
public void valueChanged( TreeSelectionEvent e ) {
process( e ); // do what you do now
// Forward the message.
for( TreeSelectionListener listener : ownListeners ) {
listener.valueChanged( e );
}
}
}
OTHER TIPS
Not a very good solution, but you can wrap code in a SwingUtilities.invokeLater(...). This will add the code to the end of the EDT, which means it will ultimately execute after the other listener code has executed.