Search code examples
javatextareaawtstringbuffer

String-based cursor positioning


How do I locate the cursor position in a Java textarea where the text is held in a StringBuffer? I am trying to implement the backspace function in a text editor. The API lists how to set data. I need to get the cursor position, to know at which character position the cursor is, not the onscreen global coordinates of the cursor.

Any assistance is sincerely appreciated.


Solution

  • You have to write KeyListeners for keypress events in the TextArea and keep a virtual cursor of where you are in the TextArea. Then map that offset into your StringBuffer, there is no magic way to do it.