Jared
Jared

Reputation: 2133

How can I force an event listener to execute last in java?

I have a JTextPane that has a DocumentListener waiting for changes to the underlying HTML document. When the content changes, the event uses JTextPane.scrollToReference to move the view to a certain reference anchor. The problem is that the underlying View in the JTextPane is also listening to the document changes, and doesn't update until after my listener executes, which causes an exception. Is there any way I can force my DocumentListener to execute after any other event listeners for that particular event? Or is there some way I can wait for the view to be updated before executing my code?

Upvotes: 3

Views: 1109

Answers (3)

Jared
Jared

Reputation: 2133

I wound up having to extend the Viewport and JScrollPane classes to accomplish this. I exposed a listener for the viewport's change event and added my logic in there (which ensured it was the last code executed in the rendering chain).

Upvotes: 0

mKorbel
mKorbel

Reputation: 109823

  • Document is model fro JTextComponents, then not good idea put there two or more Listeners wrote changes to the Document,

  • all event should be done if model invoke all implemented event to the view, then only if are all events done in the view, then is possible moving with JViewport

  • no idea whats Listener you are implemented, but DocumentListener (e.g.) with FocusListener (e.i.) can creating endless loop with nice exception from RepaintManager

  • remove Listener that generating exceptions, add Listener if is really required, remove uselles Listeners immediatelly,

  • Swing quite no guarentee ordering of Listeners, nor events from multiplayed Listeners betweens model_to_view and vice versa

  • you can testing if Listeners firing events subsequently or gradually by pushing of required event from Swing Action (delayed from Swing Timer) or for asynchronous Listeners (freezed) by Thread.sleep(int)

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68897

First try to use SwingUtilities.invokeLater() for the listener that has to be executed as last. If that doesn't work, build your own priority queue.

Upvotes: 5

Related Questions