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

moster67

Expert
Licensed User
Longtime 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.
 

moster67

Expert
Licensed User
Longtime 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....
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Better way:
B4X:
   '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
 
Upvote 0

moster67

Expert
Licensed User
Longtime User
Very nice and indeed much better!
Thanks for your usual premium support.
 
Upvote 0
Top