7

I can't find any information on how to set the menubar icon for dark mode on OS X (introduced in OS X 10.10 Yosemite) in Java. I've seen this post http://mail.openjdk.java.net/pipermail/macosx-port-dev/2014-October/006740.html but without any answer. I know this has been discussed here How to detect dark mode in Yosemite to change the status bar menu icon for Objective-C, but not sure if this can be done similarly in Java.

Is there some way to achieve this?

Community
  • 1
  • 1
tobihagemann
  • 601
  • 8
  • 15

1 Answers1

10

I’ve had the same issue, solving it by invoking the defaults read command and analyzing the exit code:

/**
 * @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;
    }
}

Now you can load different images and use them in a 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"));
}
Sebastian S
  • 4,420
  • 4
  • 34
  • 63
  • Can we do the same using python? – impossible May 09 '16 at 07:59
  • 1
    @ArewegoodQ Absolutely, the above isn't limited to Java. Just execute a new shell process and evaluate the exit value. – Sebastian S May 09 '16 at 10:38
  • Thanks for your suggestion. Would you mind answering this question? http://stackoverflow.com/questions/37108924/python-code-to-detect-dark-mode-in-yosemite-to-change-the-status-bar-menu-icon – impossible May 09 '16 at 11:04
  • For future proof, shouldn't you make sure it returns `"Dark"`? https://stackoverflow.com/questions/25207077/how-to-detect-if-os-x-is-in-dark-mode – tresf Nov 14 '18 at 02:41
  • FYI, "Big Sur" now is capable of using "light mode" for the tray icon when the desktop is in dark mode, invalidating this answer. New question posted here: https://stackoverflow.com/questions/62685948/macos-big-sur-detect-dark-menu-bar-system-tray – tresf Jul 08 '20 at 22:03