[英]Capture "quit" from dock icon in Java App
在 OS X 上(也可能在 Windows 上,但还没有尝试过),我需要通过确认来中断退出应用程序的选择。 注意:这不是窗口上的关闭按钮,而是从 Dock 图标和应用程序菜单中选择退出。 顺便说一句,如果它们不同,那么我需要两个听众。 覆盖processWindowEvent
并设置setDefaultCloseOperation()
似乎不起作用。
注意:我找到了适用于 Mac 的解决方案,并从接受的答案中包含了适用于 Windows 的代码。 见下文。
既然你提到了setDefaultCloseOoperation()
我假设你在谈论JFrame
。
这是您如何做到这一点。
this.addWindowListener(new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent)
{
int ret = JOptionPane.showConfirmDialog(MyJFrame.this, "Are you sure you want to quit?");
if(ret == JOptionPane.YES_OPTION)
{
dispose();
}
}
});
好的,如果其他人对此感兴趣,以下是我发现在我的情况下有效的方法:
编辑更新:我已经在 Windows 10 和 OSX Yosemite 上进行了测试,并且可以正常工作。 我在下面合并了 James Wierzba 的代码。
为 Apple 退出处理程序创建一个单独的类文件(Apple 库不包含在 Windows JDK 中):
import com.apple.eawt.AppEvent;
import com.apple.eawt.Application;
import com.apple.eawt.QuitHandler;
import com.apple.eawt.QuitResponse;
public class AppleQuitHandler {
public static void DoAppleQuit() {
Application a = Application.getApplication();
a.setQuitHandler(new QuitHandler() {
@Override
public void handleQuitRequestWith(AppEvent.QuitEvent quitEvent, QuitResponse quitResponse) {
int ret = JOptionPane.showConfirmDialog(null, "Are you sure");
if (ret == JOptionPane.YES_OPTION) {
// Go ahead and exit
quitResponse.performQuit();
} else {
// Return to program
quitResponse.cancelQuit();
}
}
}
};
}
有条件地向根 JFrame 添加一个监听器(Windows 退出):
String OS = System.getProperty("os.name").toLowerCase();
if(OS.contains("win")) {
myJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int ret = JOptionPane.showConfirmDialog(null, "Are you sure");
if (ret == JOptionPane.YES_OPTION) {
songFrame.dispose();
System.exit(0);
}
}
});
}
最后为 AppleQuitHandler() 添加条件:
String OS = System.getProperty("os.name").toLowerCase();
if(OS.contains("mac")) {
AppleQuitHandler.DoAppleQuit();
}
您现在应该有一个适用于 Mac 和 Windows 的工作解决方案来捕获菜单和快捷键的关闭。
注意:这没有经过彻底测试,但我确实在 Mac 和 Windows 上尝试过。
仅供参考:您需要添加 Apple 库才能在 Windows 上进行编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.