Swing applications and Mac OS X menu bar
Every once in a while i get questions on using the Mac OS X menu bar for Swing applications running under Substance look-and-feel. This refers to the apple.laf.useScreenMenuBar VM flag that is respected by the native Aqua look-and-feel (and its third-party Quaqua extension). Up until this week the only advice that i could give was to use AWT menus (thanks to Quaqua’s author Werner Randelshofer for this). However, it is not the optimal solution for cross-platform Swing applications that wish to use Swing menus on non-Mac platform.
As i was thinking about this problem after being recently contacted by Sergiy Michka, i thought about an alternative solution which was later reviewed by Swing lead for Apple VM Mike Swingler. The solution is not specific to Substance and should work under other core and third-party look-and-feels that allow mixing menu UI delegates from other look-and-feels. Here is what you can do in your Swing application to have your menus appear on the global menu bar (in addition to setting the above VM flag):
- Check that you’re running under Apple VM. Use
<font color="darkblue">System.getProperty("os.name")</font>
and check that the value starts with “Mac”. - Set Aqua (or the future default Apple VM platform look-and-feel) with
<font color="darkblue">UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())</font>
. - Query and store the following
<font color="darkblue">UIManager</font>
entries: “MenuBarUI”, “MenuUI”, “MenuItemUI”, “CheckBoxMenuItemUI”, “RadioButtonMenuItemUI”, “PopupMenuUI”. - Set your look-and-feel of preference with
<font color="darkblue">UIManager.setLookAndFeel</font>
call. - Before creating your first window, restore the
<font color="darkblue">UIManager</font>
entries for the keys specified in the third step.
Now the menus on the fronted frame will go into the global menu bar. It is not recommended to rely on the current class names for the Aqua UI delegates, since the package that hosts these classes is different for different versions of Apple VM. This is mentioned in the release notes for Apple VM 1.6.0 on Mac OS X 10.5 Leopard (radar #4907470).