Swing: listeners execution order on custom component

风格不统一 提交于 2019-12-11 06:49:58

问题


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!


回答1:


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

 }



回答2:


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.



来源:https://stackoverflow.com/questions/1460468/swing-listeners-execution-order-on-custom-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!