It is very easy to setup a MenuBar
in Compose for Desktop. But as you will see shortly, some MenuItem
s may need help from old classes. Take a look at the following code snippet. This function configures a menubar with one (if running on macOS) or two Menu
s.
private fun configureMenuBar() {
val menuBar = MenuBar()
if (!System.getProperty("os.name", "").contains("mac os x", true)) {
menuBar.add(Menu("File", MenuItem(
name = "Quit",
onClick = {
AppManager.exit()
},
shortcut = KeyStroke(Key.F4)
)))
}
menuBar.add(Menu("Appearance", MenuItem(
name = "Toggle Colors",
onClick = {
isInDarkMode = !isInDarkMode
},
shortcut = KeyStroke(Key.T)
)))
AppManager.setMenu(menuBar)
}
On macOS the app gets a Quit menu item for free. On other platforms, we need to provide it on our own.
Have you noticed the shortcut? It's Ctrl+F4, which is not quite correct as on Windows applications are closed using Alt+F4. That happens because I wrote shortcut = KeyStroke(Key.F4)
. The source code for KeyStroke()
(the file MenuItem.kt belongs to package androidx.compose.ui.window
) currently looks like this:
fun KeyStroke(key: Key): KeyStroke {
return KeyStroke.getKeyStroke(
key.keyCode,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()
)
}
The implementation of getMenuShortcutKeyMaskEx()
in Toolkit.java is as follows:
public int getMenuShortcutKeyMaskEx() throws HeadlessException {
GraphicsEnvironment.checkHeadless();
return InputEvent.CTRL_DOWN_MASK;
}
So, how to get Alt instead? We just need to invoke KeyStroke.getKeyStroke()
on our own:
shortcut = KeyStroke.getKeyStroke(
KeyEvent.VK_F4, ActionEvent.ALT_MASK)
As most menu item shortcuts should correspond to Ctrl using KeyStroke()
is fine most of the time. But if you need another modifier key, you now know how to get it.