What is an efficient way to get, modify and replace a row/line of content in a JTextArea in Java swing?

67 Views Asked by At

If you have a Java swing JTextArea with many rows/lines of content, what is a good and relatively efficient way to get the content of a row as a string using the row number, modify the string and then replace the original row with the modified one without affecting the other rows of the text area?

I was thinking about getting the text area content as a string, then splitting the string by "\n" to get a string array, modifying stringArray[row] and turning the string array back into a string and finally setting the text area's content to be the modified string. But this way seems maybe not very efficient, I think O(n) time complexity probably. Is there a more efficient way than this to modify a row in a text area? Thank you.

1

There are 1 best solutions below

0
camickr On

Is a JTextArea the correct component? Why do you need to replace the text? Maybe a JList or JTable would be better to display rows of data?

If you really need a JTextArea then changes to the data are done via the model, which is the Document of the text area.

There are method:

  1. remove(...) - to remove text
  2. insertString(...) - to insert text
  3. getText(...) - to get text

Then you can use methods of the text area to track the start/end offset of the given line in the Document:

  1. getLineStartOffset(...)
  2. getLineEndOffset(...)

Create a method that uses the above methods to accomplish your task.

Or instead of updating the Document directly, maybe a simpler solution would be to just use the replaceRange(...) method of the JTextArea. Again you would use the above methods to get the start/end offset of the text for the given line.