views:

170

answers:

2

My custom component is composed of three JTrees 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 TreeSelectionListeners to the JTrees 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!

+2  A: 

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 );
           }
    }

 }
OscarRyz
Thanks, that's a great solution! I wonder how I didn't get it before :) BTW I've got a new problem :/ (http://stackoverflow.com/questions/1466042/swing-how-can-i-ignore-deselection-events)
Giuseppe
I'm glad it was helpful. Maybe because sometimes we are too concentrated in one view of the problem that we don't see the other options. That happens to me quite often. Sometimes we just need a different point of view.
OscarRyz
A: 

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.

camickr