• Post Reply Bookmark Topic Watch Topic
  • New Topic

Event Dispatch Thread question  RSS feed

 
John Danek
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So my program consists of a JFrame with a Start button. Upon clicking the start button, I want my startSimulation() method to run, which resides in the class that created the frame. Current, I register startButton with startButtonListener. Within startButtonListener, I call the startSimulation() method in my SimulationController. But, this method has a ton of stuff to do (calculations, chart redraws, Thread.sleeps) and the frame hangs up for about 20 seconds.

I know this is because the startSimulation method is being called from within the Event Dispatch Thread. How can I make the main (default) Thread execute the startSimulation() method instead of the EventDispatchThread?

Thanks for your help, I am (obviously) new to the ideas of threading but have read up this morning in books. I would prefer to not create a new thread (since I already have the 2 I need).
 
John Danek
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found a quick fix to solving this problem. Here is the code inside my event handler:



I wish I could avoid making this new Thread, but it seems to work. If there is anyway to make the main thread call the method, I would love to know!
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wish I could avoid making this new Thread, but it seems to work.


Well, you have to take the load off of the event dispatching thread. This means that you have to either start a new thread, or pass the work to another thread that is waiting for it -- such as a threadpool.

If there is anyway to make the main thread call the method, I would love to know!


Sure, you can make you main thread wait for work, instead of terminating... but why? Isn't it better to have an executor? Or if it is a one shot deal, just start a new thread?


BTW, only the event dispatching thread can change swing components, so if your new thread saves the answer in some components, you need to pass that work back to the even dispatching thread -- see javax.swing.SwingUtilities for details (particularly the invokeXXX() methods).

Henry
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!