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

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

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

它完全符合我对上述控件的要求。这个问题与此无关。

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

假设我要扩展WindowAdaptor,然后通过addWindowListener()将适配器的一个实例添加为侦听器。我希望看到通过windowDeactivated()、windowClosing()和windowClosed()的调用序列与X close按钮相同。可以说,与其说是撕破窗户,不如说是让它自己撕毁。


当前回答

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

不太棘手。

其他回答

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

使用:setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

下面是解决方案的概要,

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

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

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

// frame stuffs here ...

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

JFrame获取要关闭的事件,并在关闭时退出。

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

在应用程序的退出点调用java方法System.exit(…) 例如,如果你的应用程序是基于框架的,你可以添加监听器WindowAdapter,并在它的方法windowClosing(WindowEvent e)中调用System.exit(…)。

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

避免意外的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);
   }
}

以下是你的选择:

System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

不太棘手。