What\'s the correct way to get a JFrame
to close, the same as if the user had hit the X
close button, or pressed Alt+F4 (on W
Exiting from Java running process is very easy, basically you need to do just two simple things:
System.exit(...)
at at application's quit point.
For example, if your application is frame based, you can add listener WindowAdapter
and and call System.exit(...)
inside its method windowClosing(WindowEvent e)
. Note: you must call System.exit(...)
otherwise your program is error involved.
System.exit(...)
at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called. This is strongly related to your programming skills.
** Following is a simplest sample (JFrame
based) which shows you how to call exit method
import java.awt.event.*;
import javax.swing.*;
public class ExitApp extends JFrame
{
public ExitApp()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args)
{
ExitApp app=new ExitApp();
app.setBounds(133,100,532,400);
app.setVisible(true);
}
}