Java中OS X上暗模式的MenuBar图标

时间:2015-11-02 12:11:28

标签: java macos

我无法找到有关如何在OS X(OS X 10.10 Yosemite中引入)中为暗模式设置菜单栏图标的任何信息。我已经看过这篇文章http://mail.openjdk.java.net/pipermail/macosx-port-dev/2014-October/006740.html,但没有任何答案。我知道这里已经为Objective-C讨论了How to detect dark mode in Yosemite to change the status bar menu icon,但不确定这是否可以用Java来完成。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:8)

我遇到了同样的问题,通过调用defaults read命令并分析退出代码来解决它:

/**
 * @return true if <code>defaults read -g AppleInterfaceStyle</code> has an exit status of <code>0</code> (i.e. _not_ returning "key not found").
 */
private boolean isMacMenuBarDarkMode() {
    try {
        // check for exit status only. Once there are more modes than "dark" and "default", we might need to analyze string contents..
        final Process proc = Runtime.getRuntime().exec(new String[] {"defaults", "read", "-g", "AppleInterfaceStyle"});
        proc.waitFor(100, TimeUnit.MILLISECONDS);
        return proc.exitValue() == 0;
    } catch (IOException | InterruptedException | IllegalThreadStateException ex) {
        // IllegalThreadStateException thrown by proc.exitValue(), if process didn't terminate
        LOG.warn("Could not determine, whether 'dark mode' is being used. Falling back to default (light) mode.");
        return false;
    }
}

现在您可以加载不同的图片并在java.awt.TrayIcon中使用它们:

// java.awt.* controls are well suited for displaying menu bar icons on OS X
final Image image;
if (isMacMenuBarDarkMode()) {
    image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/tray_icon_darkmode.png"));
} else {
    image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/tray_icon_default.png"));
}