让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,还要触发WindowListener事件,试试这个:

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获取要关闭的事件,并在关闭时退出。

以下是你的选择:

System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window

如果您希望GUI的行为就像单击X关闭按钮一样,那么您需要向window分派一个窗口关闭事件。关闭应用程序中的ExitAction允许您将此功能添加到菜单项或任何使用Actions的组件中。

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);