简体   繁体   中英

In Java, how do you exit the application only when there is no frame open?

I'm new to Java desktop application. How do I make the application exit only when there is no frame open? In VB.NET there is an option in the project properties that says "Exist when last form closes" something like that.

Basically I have two frames, Login and MainMenu. The Login shows first, and when the user successfully logged in, the Login will be closed and the MainMenu will open.

You can put all your frames in a List add a window closing event to each of the frame and remove it from the list on window close.If the list contains no element you can exit the application.

Additionally you can use setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

When you create your top-level frame, make sure you tell it what to do when it's closed, using the setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); code snippet.

Basically, in Java, if you close a window, it's just hidden, not closed, so you can re-use it. This tells Java than when this particular window is closed, you intend to exit the application.

Have you had a chance to look at the Java Swing tutorial trails? If you have a moment, browse to http://docs.oracle.com/javase/tutorial/uiswing/ - they have a lot of useful information there that might help you. Some of the Swing techniques are definitely different to what you might be used to from a .NET perspective.

place this in the JFrame constructor, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

Now for good GUI app in Java, use the below in main fun

EventQueue.invokeLater(new Runnable() {

   MyFrame f = new MyFrame();

   f.setVisible(true);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM