Java 如何以编程方式关闭 JFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1234912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:11:58  来源:igfitidea点击:

How to programmatically close a JFrame

javaswingjframe

提问by JustJeff

What's the correct way to get a JFrameto close, the same as if the user had hit the Xclose button, or pressed Alt+F4(on Windows)?

JFrame关闭a 的正确方法是什么,就像用户按下X关闭按钮或按下Alt+ F4(在 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 Xclose button would cause it to behave.

我真正想做的是使 GUI 的行为方式与按下X关闭按钮会导致它的行为方式相同。

Suppose I were to extend WindowAdaptorand 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 Xclose button. Not so much tearing up the window as telling it to tear itself up, so to speak.

假设我要扩展WindowAdaptor,然后通过addWindowListener(). 我想看到的调用相同的序列通过windowDeactivated()windowClosing()以及windowClosed()作为将与出现X关闭按钮。与其说是撕毁窗户,不如说是告诉它撕毁自己,可以这么说。

采纳答案by camickr

If you want the GUI to behave as if you clicked the Xclose button then you need to dispatch a window closing event to the Window. The ExitActionfrom Closing An Applicationallows you to add this functionality to a menu item or any component that uses Actions easily.

如果您希望 GUI 表现得如同您单击了X关闭按钮,那么您需要将窗口关闭事件分派到Window. 在ExitAction关闭应用程序,您可以将此功能添加到一个菜单项或使用任何组件Action小号容易。

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

回答by Itay Maman

 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

回答by James Schek

If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...)will do exactlywhat you want in a very abrupt, brute-force, and possibly problematic fashion.

如果按住Alt-F4或X你的意思是“立即退出应用程序,而不考虑的是什么其他的Windows或线程正在运行”,然后System.exit(...)会做正是你在一个很突然的,蛮力想要什么,并可能存在问题的方式。

If by Alt-F4 or X you mean hide the window, then frame.setVisible(false)is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.

如果 Alt-F4 或 X 表示隐藏窗口,那么frame.setVisible(false)就是“关闭”窗口的方式。该窗口将继续消耗资源/内存,但可以很快再次可见。

If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose()is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).

如果 Alt-F4 或 X 表示隐藏窗口并处理它消耗的任何资源,那么这就是frame.dispose()“关闭”窗口的方式。如果框架是最后一个可见窗口并且没有其他非守护线程在运行,则程序将退出。如果再次显示该窗口,它将不得不再次重新初始化所有本机资源(图形缓冲区、窗口句柄等)。

dispose()might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?

dispose()可能最接近您真正想要的行为。如果您的应用程序打开了多个窗口,您希望 Alt-F4 或 X 退出应用程序还是关闭活动窗口?

The Java Swing Tutorial on Window Listenersmay help clarify things for you.

Window Listeners 上Java Swing 教程可能有助于为您澄清一些事情。

回答by Alex

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

Not too tricky.

不太棘手。

回答by niranaam

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

不仅要关闭 JFrame,还要触发 WindowListener 事件,试试这个:

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

回答by Gazihan Alankus

If you have done this to make sure the user can't close the window:

如果您这样做是为了确保用户无法关闭窗口:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Then you should change your pullThePlug()method to be

那么你应该改变你的pullThePlug()方法是

public void pullThePlug() {
    // this will make sure WindowListener.windowClosing() et al. will be called.
    WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

    // this will hide and dispose the frame, so that the application quits by
    // itself if there is nothing else around. 
    setVisible(false);
    dispose();
    // if you have other similar frames around, you should dispose them, too.

    // finally, call this to really exit. 
    // i/o libraries such as WiiRemoteJ need this. 
    // also, this is what swing does for JFrame.EXIT_ON_CLOSE
    System.exit(0); 
}

I found this to be the only way that plays nice with the WindowListenerand JFrame.DO_NOTHING_ON_CLOSE.

我发现这是与WindowListenerand配合得很好的唯一方法JFrame.DO_NOTHING_ON_CLOSE

回答by stjepano

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).

以编程方式关闭 Swing 框架的最佳方法是使其行为与按下“X”按钮时的行为相同。为此,您需要实现适合您需要的 WindowAdapter,并将框架的默认关闭操作设置为不执行任何操作 (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:

您可以通过向其发送 WINDOW_CLOSING 事件以编程方式关闭框架,如下所示:

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

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

这将关闭框架,就像按下“X”按钮一样。

回答by rkd

This examples shows how to realize the confirmed window close operation.

本示例展示了如何实现确认的窗口关闭操作。

The window has a Window adapter which switches the default close operation to EXIT_ON_CLOSEor DO_NOTHING_ON_CLOSEdependent on your answer in the OptionDialog.

该窗口有一个 Window 适配器,可将默认关闭操作切换为EXIT_ON_CLOSEDO_NOTHING_ON_CLOSE取决于您在OptionDialog.

The method closeWindowof the ConfirmedCloseWindowfires a close window event and can be used anywhere i.e. as an action of an menu item

该方法closeWindowConfirmedCloseWindow触发一个关闭窗口事件,并可以在任何地方,即作为菜单项的动作

public class WindowConfirmedCloseAdapter extends WindowAdapter {

    public void windowClosing(WindowEvent e) {

        Object options[] = {"Yes", "No"};

        int close = JOptionPane.showOptionDialog(e.getComponent(),
                "Really want to close this application?\n", "Attention",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                null);

        if(close == JOptionPane.YES_OPTION) {
           ((JFrame)e.getSource()).setDefaultCloseOperation(
                   JFrame.EXIT_ON_CLOSE);
        } else {
           ((JFrame)e.getSource()).setDefaultCloseOperation(
                   JFrame.DO_NOTHING_ON_CLOSE);
        }
    }
}

public class ConfirmedCloseWindow extends JFrame {

    public ConfirmedCloseWindow() {

        addWindowListener(new WindowConfirmedCloseAdapter());
    }

    private void closeWindow() {
        processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
}

回答by peterk

You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program. When this is done you may handle the resulting event sequence exactly as you would if the user has clicked on the [x] button for an OS suppled decorated JFrame.

您必须将调用插入到 AWT 消息队列中,以便所有计时都正确发生,否则它将无法调度正确的事件序列,尤其是在多线程程序中。完成此操作后,您可以完全按照用户单击操作系统提供的装饰 JFrame 的 [x] 按钮来处理生成的事件序列。

public void closeWindow()
{
    if(awtWindow_ != null) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
            }
        });
    }
}

回答by Megatron

Based on the answers already provided here, this is the way I implemented it:

根据这里已经提供的答案,这是我实现它的方式:

JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// frame stuffs here ...

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

The JFrame gets the event to close and upon closing, exits.

JFrame 使事件关闭并在关闭时退出。