Insert text in JTextArea at caret position

Yoda picture Yoda · May 26, 2013 · Viewed 9.1k times · Source

I would like to insert text into JTextArea at the current caret position how to do it? I have found only java script tutorials.

Answer

Soley picture Soley · May 22, 2015

Using textarea.setText(); will replace the whole content of your text. Instead of that, you have to use insert() method of your text object.

textarea.insert("My String Here", textarea.getCaretPosition());

You can get the caret position by textObject .getCaretPosition() and start adding your text from there.

I also found this useful: https://stackoverflow.com/a/5255666/2655623

to sum up:

textarea.replaceSelection("");
textarea.insert("My String Here", textarea.getCaretPosition());