我有一个具有processWindowEvent方法的java swing应用程序。
以下是代码段
@Override
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
//exit application with proper error message
}
}
现在,当我的swing应用程序在Windows中启动时。
但是现在,如果在Mac中执行相同的步骤。
我想知道从任务栏( jetty )关闭java swing app时在mac中将调用的默认方法是什么?
最佳答案
没有com.apple.eawt.*
的世界
您需要改为 java.awt.Desktop
。
例如...
Desktop.getDesktop().setQuitHandler(new QuitHandler() {
@Override
public void handleQuitRequestWith(QuitEvent e, QuitResponse response) {
// Do some stuff
//response.cancelQuit();
//response.performQuit();
}
});
Desktop.getDesktop().setQuitStrategy(QuitStrategy.CLOSE_ALL_WINDOWS);
原始答案
欢迎来到“苹果以不同的方式做事”的美好世界
基本上发生的是,当您“退出”程序时,Apple调用
System.exit(0)
,基本上与使用CMD + Q时会发生的事情相同现在,Apple提供了一个API,该API提供了一些功能,您可以使用这些功能通过MacOS“配置”您的App并执行某些Apple独有的功能,问题是,...代码很难找到有关以下内容的有用信息和使用。
您正在寻找的是
com.apple.eawt.ApplictionsetQuitStrategy
。这默认调用System.exit(0)
,但是您可以将其更改为“关闭所有窗口”。在这种情况下,它将允许您捕获
WindowEvent
并执行您想做的所有事情import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Closing");
System.exit(0);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
try {
Class quitStrategies = Class.forName("com.apple.eawt.QuitStrategy");
Object quitStrategy = null;
for (Object o : quitStrategies.getEnumConstants()) {
if ("CLOSE_ALL_WINDOWS".equals(o.toString())) {
quitStrategy = o;
}
}
if (quitStrategy != null) {
Class appClass = Class.forName("com.apple.eawt.Application");
Class params[] = new Class[]{};
Method getApplication = appClass.getMethod("getApplication", params);
Object application = getApplication.invoke(appClass);
Method setQuitStrategy = application.getClass().getMethod("setQuitStrategy", quitStrategies);
setQuitStrategy.invoke(application, quitStrategy);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException ex) {
ex.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
}
}
我的一般建议是,建立一个不错的“Mac”实用程序类,该类封装您要使用并调用的功能。
还请注意,此功能在将来的版本中可能会突然消失。
应该注意的是,如果您打算拥有一个“一个所有人”的应用程序,那么您将需要使用反射,因为标准API中没有所需的API,但是如果您想发布一个“Apple”专用版本,您应该查看this,以获取有关如何在MacOS上编译代码的更多信息,因为使用...
Application.getApplication().setQuitStrategy(QuitStrategy.CLOSE_ALL_WINDOWS);
更容易编写和理解