How to Close a Java Swing Application from the Code

How to close a Java Swing application from the code

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

How to programmatically close a JFrame

If you want the GUI to behave as if you clicked the X close button then you need to dispatch a window closing event to the Window. The ExitAction from Closing An Application allows you to add this functionality to a menu item or any component that uses Actions easily.

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

How to close a GUI when I push a JButton?

Add your button:

JButton close = new JButton("Close");

Add an ActionListener:

close.addActionListner(new CloseListener());

Add a class for the Listener implementing the ActionListener interface and override its main function:

private class CloseListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
System.exit(0);
}
}

This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.

How to Close a swing application properly

use System.exit(0); causes JVM kills the application silently, OR make other threads as daemon

On button click, close the application Java GUI

You can try:

if (result == JOptionPane.YES_OPTION){
frame.dispose();
}

Also note CastException on the line 122.

Instead of

JFrame frame = (JFrame)e.getSource();

change to:

JFrame frame = new JFrame();

Closing a swing application once code is complete

You could use:

frame.dispose()

How Can A Program Close A GUI Without The Program Ending

java.awt.Window aTopLevelGUI; // Normally referenced as a JWindow, but this is what impls setVisible(boolean)

// To close the window:
aTopLevelGUI.setVisible(false);


Related Topics



Leave a reply



Submit