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.
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
JTextAreathen changes to the data are done via the model, which is theDocumentof the text area.There are method:
Then you can use methods of the text area to track the start/end offset of the given line in the Document:
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.