0

I've been coding a simulation that has a JFrame GUI for parameter input, and a separate JFrame that runs an animation of the simulation.

I update the animation together with the simulation, so the call to repaint comes from the function runsimulation()

I have added an EXIT_ON_CLOSE for my main GUI frame, and while the animation is running I can close the frame and it doesn't pop up again, but I want to know if it is possible to shut down the simulation thread when I close the animation frame.

Because currently when I close the frame the simulation keeps on running in the background and finishes properly, but I'd like the close event on the animation frame to be a "cancel simulation" as well.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Martin
  • 277
  • 2
  • 5
  • 17

1 Answers1

4

You have two choices here. One option is to make the running thread into a "Daemon" thread. This means that the thread will not keep the program running, so if you close the JFrame and exit the application it will terminate immediately.

Be aware that the long running thread could potentially get terminated abruptly and in the middle of processing things though.

The (probably better) way is to call interrupt() on the thread and have the thread check isInterrupted() at regular intervals and exit cleanly if the flag is set.

Tim B
  • 40,716
  • 16
  • 83
  • 128