在Java中为OS X的暗模式创建菜单栏图标

7
1个回答

10

我曾经遇到过同样的问题,通过调用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"));
}

我们能用Python做同样的事情吗? - impossible
1
@ArewegoodQ 当然,上述内容不仅限于Java。只需执行一个新的shell进程并评估退出值即可。 - Sebastian S
感谢您的建议。您介意回答这个问题吗? http://stackoverflow.com/questions/37108924/python-code-to-detect-dark-mode-in-yosemite-to-change-the-status-bar-menu-icon - impossible
为了未来考虑,您不应该确保它返回“Dark”吗?https://dev59.com/cV8e5IYBdhLWcg3w7uHP - tresf
请注意,现在的“Big Sur”可以在桌面处于深色模式时使用“浅色模式”来显示托盘图标,因此使得这个答案无效。新问题已发布在这里:https://dev59.com/01IG5IYBdhLWcg3w2VMZ - tresf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接