274

关闭a 的正确方法是什么JFrame,就像用户按下X关闭按钮或按下Alt+ F4(在 Windows 上)一样?

我有我的默认关闭操作设置我想要的方式,通过:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

它完全符合我对上述控件的要求。这个问题不是关于那个。

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

假设我要扩展WindowAdaptor,然后通过addWindowListener(). 我希望通过windowDeactivated()windowClosing()和看到windowClosed()X关闭按钮相同的调用序列。与其说是撕毁窗户,不如说是告诉它自己撕毁。

4

17 回答 17

360

如果您希望 GUI 的行为就像您单击了X关闭按钮,那么您需要向Window. 关闭应用程序ExitAction允许您将此功能添加到菜单项或任何轻松使用 s 的组件。Action

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
于 2009-08-05T22:00:16.827 回答
148
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

不太棘手。

于 2009-08-05T19:42:05.123 回答
27

如果 Alt-F4 或 X 的意思是“立即退出应用程序而不考虑正在运行的其他 Windows 或线程”,那么System.exit(...)将以非常突然、蛮力和可能有问题的方式完全按照您的意愿行事。

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

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

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

Window Listeners 上的Java Swing 教程可能会帮助您澄清一些事情。

于 2009-08-05T19:36:02.403 回答
15

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

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

那么你应该改变你的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); 
}

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

于 2011-03-28T02:40:18.163 回答
15

以下是您的选择:

System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window
于 2015-01-22T20:14:01.067 回答
10

退出 Java 运行过程非常简单,基本上你只需要做两件简单的事情:

  1. System.exit(...)在应用程序的退出点调用 java 方法。例如,如果您的应用程序是基于框架的,您可以在其方法中添加侦听器WindowAdapter和调用。System.exit(...)windowClosing(WindowEvent e)

注意:您必须调用,System.exit(...)否则您的程序会出错。

  1. 避免意外的 java 异常以确保可以始终调用 exit 方法。如果System.exit(...)在正确的位置添加,但并不意味着该方法总是可以被调用,因为意外的 java 异常可能会阻止该方法被调用。

这与您的编程技能密切相关。

** 以下是一个最简单的示例(JFrame基于),它向您展示如何调用退出方法

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);
   }
}
于 2016-03-08T10:13:29.023 回答
8

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

myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
于 2011-01-09T17:27:45.830 回答
7

以编程方式关闭 Swing 框架的最佳方法是使其行为类似于按下“X”按钮时的行为。为此,您需要实现适合您需要的 WindowAdapter,并将框架的默认关闭操作设置为不执行任何操作 (DO_NOTHING_ON_CLOSE)。

像这样初始化你的框架:

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);
}

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

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

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

于 2011-06-25T11:44:01.007 回答
4

如果您真的不希望您的应用程序在 JFrame 关闭时终止,那么,

采用 :setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

代替 :setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

这是解决方案的概要,

 myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
于 2016-08-11T11:43:05.500 回答
4

这个答案是由亚历克斯给出的,我想推荐它。它对我有用,另一件事是简单明了。

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
于 2016-11-13T10:52:33.960 回答
3

这个例子展示了如何实现确认窗口关闭操作。

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

closeWindow触发关闭窗口事件的方法ConfirmedCloseWindow可以在任何地方使用,即作为菜单项的操作

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));
    }
}
于 2012-10-16T21:55:10.127 回答
3

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

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

// frame stuffs here ...

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

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

于 2014-06-03T17:08:51.760 回答
2

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

public void closeWindow()
{
    if(awtWindow_ != null) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
            }
        });
    }
}
于 2012-12-27T17:21:28.927 回答
2

我已经尝试过了,为formWindowClosing()事件编写自己的代码。

 private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
    int selectedOption = JOptionPane.showConfirmDialog(null,
            "Do you want to exit?",
            "FrameToClose",
            JOptionPane.YES_NO_OPTION);
    if (selectedOption == JOptionPane.YES_OPTION) {
        setVisible(false);
        dispose();
    } else {
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    }
}    

这会询问用户是否要退出框架或应用程序。

于 2016-09-01T11:14:52.333 回答
1
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
于 2009-08-05T18:48:59.473 回答
1

将问题正文中的内容发布为 CW 答案。

想分享一下结果,主要来源于关注camickr的链接。基本上我需要WindowEvent.WINDOW_CLOSING在应用程序的事件队列中抛出一个。这是解决方案的概要

// closing down the window makes sense as a method, so here are
// the salient parts of what happens with the JFrame extending class ..

    public class FooWindow extends JFrame {
        public FooWindow() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(5, 5, 400, 300);  // yeah yeah, this is an example ;P
            setVisible(true);
        }
        public void pullThePlug() {
                WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
                Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
        }
    }

// Here's how that would be employed from elsewhere -

    // someplace the window gets created ..
    FooWindow fooey = new FooWindow();
    ...
    // and someplace else, you can close it thusly
    fooey.pullThePlug();
于 2014-08-27T11:40:45.560 回答
1

如果您不希望应用程序在 JFrame 关闭时终止,请使用: setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

而不是:setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

从文档中:

DO_NOTHING_ON_CLOSE (defined in WindowConstants): 什么都不做;要求程序在注册的WindowListener对象的windowClosing方法中处理操作。

HIDE_ON_CLOSE (defined in WindowConstants):调用任何注册的 WindowListener 对象后自动隐藏框架。

DISPOSE_ON_CLOSE (defined in WindowConstants):在调用任何注册的 WindowListener 对象后自动隐藏和处置框架。

EXIT_ON_CLOSE (defined in JFrame):使用系统退出方法退出应用程序。仅在应用程序中使用它。

可能仍然有用:setVisible(false)如果要再次显示同一帧,可以在 JFrame 上使用。否则调用dispose()以删除所有本机屏幕资源。

抄自彼得朗

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

于 2015-07-25T11:47:13.903 回答