使用 JFrame/Swing 实现 macOS 退出时隐藏行为

Implement macOS hide on quit behavior with JFrame/Swing

我正尝试在我的 Java JFrame 应用程序中实现“退出时图标化”行为,就像大多数本机 macOS 应用程序一样,但我很困惑。

我试过

Window.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent Event) {
        System.out.println("Closed on macOS, iconifiying");
        Window.setExtendedState(Frame.ICONIFIED);
    }
});

并在退出时关闭 window(以及添加调用 setVisible(false) 的 window 侦听器)

Window.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

前者不起作用,因为它看起来已最小化并创建了 2 个单独的图标。后者没有,因为我找不到一种方法来检测何时单击停靠图标以取消隐藏 window。如果我能弄清楚如何这样做,我更喜欢这种方法。有人知道怎么做吗?

Oh, I forgot to really specify what the behavior I'm trying to mimic really was. When you press the quit button on macOS, the window is made invisible. When you click the app's icon in the dock the window should be made visible again.

您真的应该阅读 JavaDocs,它和一点谷歌搜索让我想到了这个简单的例子...

import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.desktop.AppReopenedEvent;
import java.awt.desktop.AppReopenedListener;
import java.awt.desktop.QuitStrategy;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();

        Desktop.getDesktop().setQuitStrategy(QuitStrategy.CLOSE_ALL_WINDOWS);
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                Desktop.getDesktop().addAppEventListener(new AppReopenedListener() {
                    @Override
                    public void appReopened(AppReopenedEvent e) {
                        frame.setVisible(true);
                    }

                });
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setBorder(new EmptyBorder(32, 32, 32, 32));
            setLayout(new GridBagLayout());
            add(new JLabel("Now you see me"));
        }

    }
}