This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't main method return after GUI is created?  RSS feed

 
Bryan Incognito
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question that's been bugging me for a while...

It occurred to me that I don't know why my main method does not return until *after* I close my GUI window.

Typical code is like this:

public static void main(String[] args){
JFrame frame = new JFrame();
// configure frame size and exit on close
// make and register a bunch of components, like buttons, etc.

frame.setVisible(true);
// some other program logic here
}

So, after the frame is made visible, my program window appears. Then other stuff in main happens.

So, what's going on? Why doesn't my main method reach its end, and then the program end? How come the JFrame variable doesn't go out of scope? What's holding the main method in execution state?

Thanks, I appreciate explanations that you can give.


Bryan
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's happening is multiple threads. When you create a GUI (specifically, I think you have to make a window visible or pack it) Swing launches a thread called the EDT (Event Dispatch Thread), a non-daemon thread. And as you may be aware, the JVM will not exit until all non-daemon threads terminate.

So your main method *is* returning and the "main" thread is terminating, but the EDT keeps the JVM alive and keeps your frame from being GC'ed.
 
Bryan Incognito
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Jeff!

That's kind of what I was expecting, that there was some other thread, or maybe some sort of other reference in some JVM static something or other...

Thanks for your clear explanation.


Bryan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!