Joris Kluivers

I like to build software.

Global Menu Bar on OS X When Using Swing

On windows and linux the menu bar is usually attached to the window. On OS X however the menubar is always at the top of the screen. When creating an application using Java and Swing the menu bar will be attached to the window by default, even when you run the application on OS X.

All OS X applications also have an application name named after the application with menu items like Hide Application, Preferences and Quit. When using java the application menu is named after the main class which can be quite user unfriendly.

To make a Java Swing application more like a native application on Mac OS X you can use the following system properties use a global menu and change the application name in the application menu. The System.setProperty calls are wrapped in a try/catch block to prevent errors in a Web Start application.

I usually add this code to my main method. You can use this code anywhere else, but beware, you have to set the properties before using any Swing classes, otherwise it won’t work. So setting the properties in a main method in a class that extends from JFrame won’t work, because the extended JFrame is loaded in the static context before any properties are set in you main method.

try {
  System.setProperty( "", "Ted" );
  System.setProperty( "", "true" );
  System.setProperty( "apple.laf.useScreenMenuBar", "true" ); // for older versions of Java
} catch ( SecurityException e ) {
  /* probably running via webstart, do nothing */