[英]How to programmatically close a JFrame
關閉JFrame
的正確方法是什么,就像用戶按下X
關閉按鈕或按下Alt + F4 鍵 (在Windows上)一樣?
我通過以下方式設置了我想要的默認關閉操作:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
它完全符合我想要的上述控件的功能。 這個問題不是關於這個的。
我真正想做的是使GUI的行為與按X
關閉按鈕的行為相同。
假設我要擴展WindowAdaptor
,然后通過addWindowListener()
適配器的實例添加為偵聽器。 我希望通過windowDeactivated()
, windowClosing()
和windowClosed()
看到與X
關閉按鈕相同的調用序列。 可以說,與其說是要把窗戶自己撕開,還不如說是要撕開窗戶。
如果希望GUI像單擊X
關閉按鈕一樣工作,則需要向Window
調度一個窗口關閉事件。 通過關閉應用程序的ExitAction
,您可以將此功能添加到菜單項或使用Action
的任何組件中。
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
不太棘手。
如果用Alt-F4或X表示“不考慮正在運行的其他Windows或線程正在運行而立即退出應用程序”,那么System.exit(...)
將以一種非常突然的蠻力來完全滿足您的要求,甚至可能是有問題的時尚。
如果按Alt-F4或X表示隱藏窗口,則frame.setVisible(false)
是“關閉”窗口的方式。 該窗口將繼續消耗資源/內存,但可以很快使其再次可見。
如果用Alt-F4或X表示隱藏窗口並處置其消耗的任何資源,則frame.dispose()
是“關閉”窗口的方式。 如果該框架是最后一個可見窗口,並且沒有其他非守護程序線程在運行,則程序將退出。 如果再次顯示該窗口,它將不得不再次重新初始化所有本機資源(圖形緩沖區,窗口句柄等)。
dispose()
可能最接近您真正想要的行為。 如果您的應用程序有多個打開的窗口,您是否要讓Alt-F4或X退出應用程序或僅關閉活動窗口?
有關窗口偵聽器的Java Swing教程可能會幫助您澄清一些事情。
如果您這樣做是為了確保用戶無法關閉窗口:
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
和JFrame.DO_NOTHING_ON_CLOSE
配合使用的唯一方法。
這是您的選擇:
System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window
退出Java運行過程非常容易,基本上,您只需要做兩件事即可:
System.exit(...)
。 例如,如果您的應用程序是基於框架的,則可以添加偵聽器WindowAdapter
並在其方法windowClosing(WindowEvent e)
內調用System.exit(...)
windowClosing(WindowEvent e)
。 注意:您必須調用System.exit(...)
否則您的程序會出錯。
System.exit(...)
,但這並不意味着可以始終調用該方法,因為意外的Java異常可能會阻止該方法被調用。 這與您的編程技能密切相關。
**以下是最簡單的示例(基於JFrame
),向您展示如何調用exit方法
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);
}
}
不僅要關閉JFrame,還要觸發WindowListener事件,請嘗試以下操作:
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
不僅關閉JFrame,而且關閉整個應用程序,因此“ EXIT ON CLOSE”
要獲得相同的結果,您必須有效退出應用程序,為此只需調用
System.exit(0);
效果是完全一樣的。
如果您確實不希望在關閉JFrame時終止應用程序,
使用: setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
而不是: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
這是解決方案的概要,
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
以編程方式關閉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”按鈕那樣關閉框架。
本示例說明如何實現確認的窗口關閉操作。
該窗口具有切換默認的關閉操作的窗口適配器EXIT_ON_CLOSE
或DO_NOTHING_ON_CLOSE
依賴於你的答案OptionDialog
。
ConfirmedCloseWindow
closeWindow
方法會觸發關閉窗口事件,並且可以在任何地方使用,例如,作為菜單項的操作
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));
}
}
根據此處已經提供的答案,這是我實現它的方式:
JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame stuffs here ...
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
JFrame使事件關閉,並在關閉時退出。
這個答案是亞歷克斯給出的,我想推薦它。 它對我有用,而另一件事則非常簡單。
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
您必須將調用插入到AWT消息隊列中,以便所有計時都正確發生,否則它將不會分派正確的事件序列,尤其是在多線程程序中。 完成此操作后,您可以完全按照用戶單擊操作系統裝飾好的JFrame的[x]按鈕時所處理的事件序列來處理結果。
public void closeWindow()
{
if(awtWindow_ != null) {
EventQueue.invokeLater(new Runnable() {
public void run() {
awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
}
});
}
}
我已經試過了,為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);
}
}
這詢問用戶是否要退出框架或應用程序。
將問題正文中的內容發布為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();
如果您不希望應用程序在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)
:使用系統退出方法退出應用程序。 僅在應用程序中使用它。
可能仍然有用:如果要再次顯示同一幀,可以在JFrame上使用setVisible(false)
。 否則,調用dispose()
刪除所有本機屏幕資源。
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.