B4J Question How to add a shortcut to a menu item with code

xulihang

Active Member
Licensed User
Longtime User
If a menu item already has a shortcut defined in the layout file, I can modify the shortcut with the following code:

B4X:
Dim menu As Menu = MenuBar1.Menus.Get(0)
Dim mi As MenuItem = menu.MenuItems.Get(1)
Dim jo As JavaObject = mi
Dim KeyCombination As JavaObject
KeyCombination.InitializeStatic("javafx.scene.input.KeyCombination")
jo.RunMethod("setAccelerator",Array(KeyCombination.RunMethod("keyCombination",Array("Ctrl+T"))))

Now I need to add a shortcut to a menu item which does not have a predefined shortcut. I've tried the following code but it does not work. Any help would be appreciated.

B4X:
Sub setEvent(menuItem as JavaObject)
    Dim e As JavaObject
    e = menuItem.CreateEvent("javafx.event.EventHandler","mi",False)
    menuItem.RunMethod("setOnMenuValidation",Array(e))
End Sub

Sub mi_Event(MethodName As String, Args() As Object)
    Log(MethodName)
End Sub
 
Solution
It appears that you can't add a shortcut to a menuitem once the menuitem has been added to the menu. It looks like you can change the shortcut as you have already done.

This is a workaround that works. Replace the menuitem with a new instance.

B4X:
    Dim menu As Menu = MenuBar1.Menus.Get(0)
    Dim mi As MenuItem
    mi.Initialize("Save","MenuBar1")
    Dim KeyCombination As JavaObject
    KeyCombination.InitializeStatic("javafx.scene.input.KeyCombination")
    mi.As(JavaObject).RunMethod("setAccelerator",Array(KeyCombination.RunMethod("keyCombination",Array("Ctrl+T"))))
    menu.MenuItems.Set(1,mi)

B4X:
Public Sub MenuBar1_Action
    Log(Sender.As(MenuItem).Text & " fired")
End Sub

stevel05

Expert
Licensed User
Longtime User
It appears that you can't add a shortcut to a menuitem once the menuitem has been added to the menu. It looks like you can change the shortcut as you have already done.

This is a workaround that works. Replace the menuitem with a new instance.

B4X:
    Dim menu As Menu = MenuBar1.Menus.Get(0)
    Dim mi As MenuItem
    mi.Initialize("Save","MenuBar1")
    Dim KeyCombination As JavaObject
    KeyCombination.InitializeStatic("javafx.scene.input.KeyCombination")
    mi.As(JavaObject).RunMethod("setAccelerator",Array(KeyCombination.RunMethod("keyCombination",Array("Ctrl+T"))))
    menu.MenuItems.Set(1,mi)

B4X:
Public Sub MenuBar1_Action
    Log(Sender.As(MenuItem).Text & " fired")
End Sub
 
Upvote 1
Solution
Top