How to programmatically close a JFrame

2018-12-31 07:54发布

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 Windows)?

I have my default close operation set the way I want, via:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

It does exactly what I want with the aforementioned controls. This question isn't about that.

What I really want to do is cause the GUI to behave in the same way as a press of X close button would cause it to behave.

Suppose I were to extend WindowAdaptor and then add an instance of my adaptor as a listener via addWindowListener(). I would like to see the same sequence of calls through windowDeactivated(), windowClosing(), and windowClosed() as would occur with the X close button. Not so much tearing up the window as telling it to tear itself up, so to speak.

18条回答
无色无味的生活
2楼-- · 2018-12-31 08:14

Here would be your options:

System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window
查看更多
深知你不懂我心
3楼-- · 2018-12-31 08:14

Not only to close the JFrame but also to trigger WindowListener events, try this:

myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
查看更多
刘海飞了
4楼-- · 2018-12-31 08:14
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
查看更多
只靠听说
5楼-- · 2018-12-31 08:16

Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).

Initialize your frame like this:

private WindowAdapter windowAdapter = null;

private void initFrame() {

    this.windowAdapter = new WindowAdapter() {
        // WINDOW_CLOSING event handler
        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            // You can still stop closing if you want to
            int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
            if ( res == 0 ) {
                // dispose method issues the WINDOW_CLOSED event
                ClosableFrame.this.dispose();
            }
        }

        // WINDOW_CLOSED event handler
        @Override
        public void windowClosed(WindowEvent e) {
            super.windowClosed(e);
            // Close application if you want to with System.exit(0)
            // but don't forget to dispose of all resources 
            // like child frames, threads, ...
            // System.exit(0);
        }
    };

    // when you press "X" the WINDOW_CLOSING event is called but that is it
    // nothing else happens
    this.setDefaultCloseOperation(ClosableFrame.DO_NOTHING_ON_CLOSE);
    // don't forget this
    this.addWindowListener(this.windowAdapter);
}

You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:

WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);

This will close the frame like the "X" button was pressed.

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 08:17

Exiting from Java running process is very easy, basically you need to do just two simple things:

  1. Call java method 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.

  1. Avoiding unexpected java exceptions to make sure the exit method can be called always. If you add 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);
   }
}
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 08:18

If you do not want your application to terminate when a JFrame is closed, use: setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

instead of: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

From the documentation:

DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.

HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.

DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.

EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.

copied from Peter Lang

https://stackoverflow.com/a/1944474/3782247

查看更多
登录 后发表回答