[英]How can I stop the closing of a Java application
我有一個Java桌面應用程序,我想當用戶選擇退出時會彈出一個窗口,詢問他是否要繼續關閉應用程序。 我知道如何使窗口出現並讀取用戶的響應,但我需要知道的是如何阻止應用程序關閉(類似於System.close().cancel()
)。
那可能嗎?
對的,這是可能的。
調用setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)
,添加一個WindowListener
或WindowAdapter
並在windowClosing(WindowEvent)
方法中彈出一個JOptionPane
。
int result = JOptionPane.showConfirmDialog(frame, "Exit the application?");
if (result==JOptionPane.OK_OPTION) {
System.exit(0);
}
設置setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
到你的JFrame或JDialog,添加一個Windows監聽器:
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
int result = JOptionPane.showConfirmDialog((Component) null, "Do u really want to exit ?!",
"Confirmation", JOptionPane.YES_NO_OPTION);
if (result == 0) {
System.exit(0);
} else {
}
}
});
您可以添加窗口偵聽器。 (注意: WindowAdapter
在java.awt.event
包中)
myframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// do something
}
});
在JFrame
,您必須設置defaultCloseOperation
:
JFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
然后將彈出窗口的關閉操作設置為EXIT_ON_CLOSE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.