Shutting Down from the OSX Application Menu

On OS X, there are two kinds of menus:

  1.   Application-specific ones you define yourself
  2.   The Application menu all applications get from OS X
The Application Menu

This is a non-issue on Linux and Windows, as there is no application menu. You create your own “quit application” menu item in JavaFX to shutdown you application and that’s it.

Unfortunately, JavaFX has limited support for configuring or using the OS X application menu. So what can you do with the application menu on OS X?

  1. Set the menu name (via tools like the javapackager tool)
  2. Process some events and add handlers via Apple specific JDK packages (via com.apple.eawt package)
  3. Use the JavaFX stage.setOnCloseRequest to handle the quit event

I will describe how to add a CloseRequest handler to application’s primary stage, as this took me the longest time to figure out how to do. This will enable you to shutdown your JavaFX Application when it has been installed as a real OS X Application. Once you know how, it’s dead simple. The only reason for this blog post is that it took me longer than expected to find this out. Maybe it was a bad day, or maybe I’m just an idiot. Either way, if I had some trouble getting to the bottom of it, no doubt someone else did as well.

In my flimsy defence, I had only done something similar in Swing before, and a search on StackOverflow resulted in questions related to, but not exactly answering the question.

Here is the logic for your main application class. That’s it. Embarrassing really.

 override fun start(stage: Stage) { 
 ...
  stage.setOnCloseRequest { 
    shutdown() 
  } 
  ...
}

fun shutdown() { 
  // your additional shutdown logic
  Platform.exit()
}

JavaFX appears to know which operating system is running and automatically uses the system menu bar if possible (unlike Swing). So, no need for code like this anymore:

if(System.getProperty("os.name").contains("mac"))
   menuBar.isUseSystemMenuBartrue 
else
   menuBar.isUseSystemMenuBarfalse 

Other Implications

I took a look at a few other OS X applications, and confirmed they only had a Quit Application menu item in the application menu, and nowhere else. I spend so much time hitting the ⌘-Q key (a habit learned way back in 1985), I never pay much attention to the quit menu items.

So, if you have a ‘Quit’ menu item in you JavaFX menu (expected for operating systems other than OS X), don’t show it on OS X – you only need it for Windows and Linux versions.