B4J Question TextArea - how to get Caret(Cursor) position in a SelectionChanged event

Discussion in 'B4J Questions' started by moster67, Feb 25, 2019.

  1. moster67

    moster67 Expert Licensed User

    I am using a TextArea in a project and I would like to show the current position of the caret/cursor when moving around in the text area with the arrow keys on the keyboard. I would also like to get the position when I click in the TextArea using the mouse.

    I think to do this, I need to get the caretPosition exposed and also the necessary events to use for tracking the position.

    Basically, I want to show the current caret position in a label like this: Pos 2/3500 where 3500 is TextArea.text.length.
     
  2. moster67

    moster67 Expert Licensed User

    Ok, it is possible using a timer and getting the value from "txtArea.SelectionStart".
    I would have thought that there would be a more "proper" way to get it since using the timer feels more like a hack to me....
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    Better way:
    Code:
    'AppStart
        Dim jo As JavaObject = TextArea1
       
    Dim event As Object = jo.CreateEventFromUI("javafx.beans.value.ChangeListener""SelectionChanged"Null)
       jo.RunMethodJO(
    "selectionProperty"Null).RunMethod("addListener"Array(event))
    End Sub

    Sub SelectionChanged_Event (MethodName As String, Args() As Object) As Object
       
    If MethodName = "changed" Then
           
    Dim IndexRange As JavaObject = Args(2)
           
    Dim StartPosition As Int = IndexRange.RunMethod("getStart"Null)
           
    Dim EndPosition As Int = IndexRange.RunMethod("getEnd"Null)
           
    Log($"${StartPosition} -> ${EndPosition}"$)
       
    End If
       
    Return Null   
    End Sub
     
    moster67 and jimmyF like this.
  4. moster67

    moster67 Expert Licensed User

    Very nice and indeed much better!
    Thanks for your usual premium support.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice