B4J Question How to invoke the event for Sender ?

peacemaker

Expert
Licensed User
Longtime User
Buttons are created dynamically, the single shared event. And key pressing are caught.


B4X:
Private Sub butVar_Click
    Dim b As B4XView = Sender
...

Private Sub KeyPressed_Event(e As Event)
    Dim KE As Reflector
    KE.Target = e 'e is a KeyEvent instance
    Dim KeyCode As String = KE.RunMethod("getCode")
    'Log(KeyCode)
    Dim EventType As String = KE.RunMethod("getEventType")
 
    Select EventType
    
        Case "KEY_PRESSED"
            For i = 0 To 9
                If KeyCode = $"DIGIT${i}"$ Or KeyCode = $"NUMPAD${i}"$ Then
                    ClickButton(i)
                    Exit
                End If

            Next
 
        Case "KEY_RELEASED"     
    End Select
    e.Consume
End Sub
...

But how to invoke butVar_Click for each button according to the keycode via ClickButton(i)?
 
Last edited:

teddybear

Well-Known Member
Licensed User
I don't know how you dynamically create buttons, but you can add a keypressed handler event when creating them.

B4X:
    For i=0 To n
        Dim btn As Button
        btn.Initialize("")
        btn.Tag=i
        ...'Create btn views
        Dim r As Reflector
        r.Target = btn
        r.AddEventHandler("btn_KeyPressed", "javafx.scene.input.KeyEvent.KEY_PRESSED")
    Next
    ...
    Private Sub btn_KeyPressed_Event(e As Event)
    Dim b As Button=Sender
    Log(b.Tag)
    Dim KE As Reflector
    KE.Target = e 'e is a KeyEvent instance
    Dim KeyCode As String = KE.RunMethod("getCode")
    'Log(KeyCode)
    Dim EventType As String = KE.RunMethod("getEventType")
 
    Select EventType
   
        Case "KEY_PRESSED"
            For i = 0 To 9
                If KeyCode = $"DIGIT${i}"$ Or KeyCode = $"NUMPAD${i}"$ Then
                    ClickButton(i)
                    Exit
                End If

            Next
 
        Case "KEY_RELEASED"    
    End Select
    e.Consume
End Sub
...
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Yes, buttons created by this way. Question is how to run buttons actions if the one single event without a parameter.
 
Upvote 0

teddybear

Well-Known Member
Licensed User
Yes, buttons created by this way. Question is how to run buttons actions if the one single event without a parameter.
It can also capture the keypress event of a specific button. could you upload a small project for that?
 
Upvote 0

teddybear

Well-Known Member
Licensed User
I got you. it should work for you.
B4X:
Sub ClickButton(i As Int)
    For Each b As Button In created_buttons
        If i-1 = b.Tag Then
            b.As(JavaObject).RunMethod("fire", Null)
            Exit
        End If
    Next
End Sub
 
Last edited:
Upvote 0
Top