Pages

Saturday, February 6, 2021

"Poor man's" dark mode detection

 Aloha,

I recently read a lot about how to detect the dark mode on MacOS or Windows from Java which is really interesting when you develop desktop applications in Java (yes they still exists).

And there are different ways in figuring this out, one of them is to use jSystemThemeDetector which not only detects the theme but also gives you the ability to listen to changes of the theme. This little library makes use of different other libraries like OSHI, JFA, Jetbrains Annotations and JNA. 

Because I also wrote a little tool that helps me to figure out the system color theme I thought I might share this with you.

So my approach is a bit different in the way that I simply make use of the already existing operating systems tools to get the information I need. If you don't need to listen to theme switches (which is usually the case because users do not change their theme all the time) but only need to know if the operating system is currently using the dark theme or the light theme then you might want to use my approach.

I simply call operating system routines on the command line using Java's Runtime.getRuntime().exec() method and parse the result.

Because I'm on MacOS I've also added the ability to get the current accent color that is used in MacOS which is useful if your application should be as close to the native MacOS apps as possible.

Because the JavaFX stage does not recognize the current MacOS theme means you have to draw the window frame on your own dependent on the current theme but that's fine. I might add another blogpost about the native looking MacOS windows frame I've created.

The thing that I like most about my little tool is that it is only one class that offers some utility methods and everything is plain Java without any dependencies. 

It works on MacOS and Windows 10 and for those of you that are interested in that tool, I've created a little gist.

At the moment this utility class is made for JavaFX but it should be easy to change the Color definitions from JavaFX to Java Swing if you need them :)

That's it for today, enjoy your weekend and keep coding... :)

No comments:

Post a Comment