website/content/blog/2017-06-05-using-system-themes-java-swing.md

2.7 KiB
Raw Blame History

id title date author layout guid aliases permalink medium_post mf2_syndicate-to mf2_cite tumblr_post_id mf2_syndication kind
2192 Using System Themes In Java Swing 2017-06-05T20:36:22+00:00 Brandon Rozek post https://brandonrozek.com/?p=2192
/2017/06/using-system-themes-java-swing/
/2017/06/using-system-themes-java-swing/
O:11:"Medium_Post":11:{s:16:"author_image_url";N;s:10:"author_url";N;s:11:"byline_name";N;s:12:"byline_email";N;s:10:"cross_link";N;s:2:"id";N;s:21:"follower_notification";N;s:7:"license";N;s:14:"publication_id";N;s:6:"status";N;s:3:"url";N;}
a:1:{i:0;s:4:"none";}
a:4:{s:9:"published";s:25:"0000-01-01T00:00:00+00:00";s:7:"updated";s:25:"0000-01-01T00:00:00+00:00";s:8:"category";a:1:{i:0;s:0:"";}s:6:"author";a:0:{}}
161478693279
a:1:{i:0;s:60:"https://twitter.com/B_RozekJournal/status/871828083459936257";}
article

The default theme for Java Swing components is a cross-platform theme called “Metal”. I use the Adapta theme for GTK on Linux and this theme does not match at all what my other GUI applications look like. So here, I will describe a simple way to utlize already existent system themes in Java Swing applications.

Solution

In the init method of your java application, place the following code.


try {
    UIManager.setLookAndFeel(UIManager
                               .getSystemLookAndFeelClassName());
} catch(Exception e) {}

Here the application will attempt to look up the system theme and set that as the default styles for the Swing components. If the lookup fails, then it will default back to the metal theme.

For more information, check out this page from Oracle.

Discussion

If it is so easy to set up applications that look native to each desktop environment, why not have that by default? With the cross platform metal theme, you can ensure that the style of your application is the same across all the operating systems. In this fashion, you dont need to worry about spacing between components and have full control of the “look and feel” of your application.

Since I am used to development for the web, I dont have strong motivation to have an application look the same on all platforms. I prefer the application to match the system theme and look like it was built for the platform that I am on. One loses partial control on the presentation of your application across different desktop environmnets, but with a strong layout, it is possible to make it look organized and integrated.