Usually one is looking for a way to update the UI while something in the background is still working. My approach there would be either use a new thread or simply use SwingUtilities.invokeLater
.
However, right now I'm in the completely opposite situation. I have a button that calls a static method which does some magic (not important here). Pressing the button also starts an animation on the UI thread (currently implemented using a Swing Timer). When the magic method is finished, it first fires an event to the UI and then continues doing something else. The event tells the UI to stop the animation - after some delay (actually the UI is supposed to show a different animation for a short time).
That delay however is exactly the problem, because I want to prevent the magic method from continuing before the animation has finished. The event listener call is currently implemented synchronizely, so the event listener won't return before it completes. But as the animation is asynchronous, I don't know how to block the background process for that time. I thought I could use a ReentrantLock to make it synchronized, but when I tried to lock it from the UI thread, that lock was ignored.
What is the correct way to make the background process wait for the UI?
edit
The code below shows extremely simplified what happens. The UI is just one of the actual listeners (the only blocking one though), so I would rather have some blocking effect on the UI side of the event handling.
public class Worker
{
public static void magicMethod()
{
// do something
// ...
// fire event
for ( ExampleEventListener listener : listeners )
listener.onExampleEvent( new ExampleEvent() );
// BLOCK until animation in UI completed
nextStep();
}
public static void nextStep ()
{
// continue work
}
}
public class MyWindow extends JFrame implements ExampleEventListener
{
public void actionPerformed ( ActionEvent event )
{
// button clicked
Worker.magicMethod();
}
public void onExampleEvent ( ExampleEvent event )
{
startAsynchronousAnimation();
}
private void completeAnimation ()
{
// animation completed
animationPanel.setVisible( false );
// UNLOCK
}
}