B4J Question AddEventHandler (keypressed) and AddChangeListener (focusProperty) don't work together

Wojtekbut

New Member
Hi,
I have some set of textfields and choiceboxes to multiple enter same data structure (name, surname and goalkeeper yes/no).
I want to go to next field by ENTER key - I use AddEventHandler (keypressed), but I must know witch field has focus to continue to the next field (when I get focus by mouse or TAB key and break order by enter key). To achieve this I use AddChangeListener (focusProperty). Each of them works good when works alone, but they dont want to work together.
Here is the example. If You comment AddFocusListener or AddKeyPressedListener the program works, but if both are active program crash.
Please help me, what am I doing wrong.
 

Attachments

  • testFocus.zip
    3.4 KB · Views: 100

Erel

B4X founder
Staff member
Licensed User
Longtime User
It happens in debug mode. It is related to the focus changed event being raised in the middle of another event.

Your code can be implemented in a much simpler way:
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI 
    Private listaOdwrotna As List
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    listaOdwrotna.Initialize
    For Each tex1 As B4XView In MainForm.RootPane.GetAllViewsRecursive
        If tex1 Is TextField Then
            listaOdwrotna.Add(tex1)
        Else If tex1 Is ChoiceBox Then
            tex1.As(ChoiceBox).Items.AddAll(Array As String("NIE","TAK"))
            tex1.As(ChoiceBox).SelectedIndex = 0
            listaOdwrotna.Add(tex1)
        End If
    Next
    AddKeyPressedListener
End Sub

Sub AddKeyPressedListener
    Dim r As Reflector
    For Each target As B4XView In listaOdwrotna
        r.Target = target
        r.AddEventHandler("keypressed", "javafx.scene.input.KeyEvent.KEY_PRESSED")
    Next
End Sub


Sub KeyPressed_Event (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    If keycode = "ENTER" Then
        Dim FocusedView As B4XView = GetFocusedView
        If FocusedView.IsInitialized Then
            Dim i As Int = listaOdwrotna.IndexOf(FocusedView)
            listaOdwrotna.Get((i + 1) Mod listaOdwrotna.Size).As(B4XView).RequestFocus
        End If
    End If
End Sub

Private Sub GetFocusedView As B4XView
    Return MainForm.As(JavaObject).GetFieldJO("scene").RunMethod("getFocusOwner", Null)
End Sub
 
Upvote 0
Top