Sunday, September 14, 2008

Using reflection to integrate with the OS X application menu

It took a while for me to find this solution, so I figured I'd post it.

The Java Swing application I've been working on at Aspera had been using the com.apple.mrj and com.apple.eawt libraries to handle OS X events such as the user selecting About, Preferences, or Quit from the Application Menu. The MRJ library is actually deprecated, but I was using it to prevent the default dialog from popping, because I didn't know you have to call setHandled() on the event, but I digress.

Apple actually provides a pretty neat solution that allows you to use com.apple.eawt without breaking builds on other platforms. It uses reflection to make the Apple-specific com.apple.eawt calls, so your application doesn't have to import them.

To integrate with their code, you just have to add the OSXAdapter.java class from their sample to your application. Then register for the events you want to handle (see the registerForMacOSXEvents() method in the irexample file MyApp.java), and specify the method you want to get callbacks for that event on.

More on integrating Java (Swing/SWT) with OS X in Apple's guide.

No comments: