B4J Code Snippet B4XDialog - Add keyboard handling

This code allows the user to close the dialog with 'escape' or one of the following keys: Y, N or C.
It depends on agraham's jReflection library.

B4X:
Sub AddKeyPressedListener
   Dim r As Reflector
   r.Target = MainForm.RootPane
   r.AddEventHandler("keypressed", "javafx.scene.input.KeyEvent.KEY_PRESSED")
End Sub

Sub KeyPressed_Event (e As Event)
   If Dialog.Visible Then
       Dim jo As JavaObject = e
       Dim keycode As String = jo.RunMethod("getCode", Null)
       If keycode = "ESCAPE" or keycode = "C" Then
           Dialog.Close(xui.DialogResponse_Cancel)
       Else If keycode = "Y" Then
           Dialog.Close(xui.DialogResponse_Positive)
       Else If keycode = "N" Then
           Dialog.Close(xui.DialogResponse_Negative)
       End If
   End If
End Sub

You need to call AddKeyPressedListener once when the program starts.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
A better solution that makes the dialog more "modal" and doesn't allow the user to switch to other fields:
B4X:
Sub AddKeyPressedListener
   Dim r As Reflector
   r.Target = MainForm.RootPane
   r.AddEventFilter("keypressed", "javafx.scene.input.KeyEvent.ANY")
End Sub

Sub KeyPressed_Filter (e As Event)
   If Dialog.Visible Then
       Dim jo As JavaObject = e
       Dim EventType As String = jo.RunMethodJO("getEventType", Null).RunMethod("getName", Null)
       If EventType = "KEY_RELEASED" Then
           Dim keycode As String = jo.RunMethod("getCode", Null)
           If keycode = "ESCAPE" Then
               Dialog.Close(xui.DialogResponse_Cancel)
           Else If keycode = "Y" Then
               Dialog.Close(xui.DialogResponse_Positive)
           Else If keycode = "N" Then
               Dialog.Close(xui.DialogResponse_Negative)
           End If
       End If
       e.Consume
   End If
End Sub

This code is useful for dialogs that don't accept text input.
 
Last edited:
Top