how to insert or append new line on top of the jtextarea in java swing?

sandybarasker picture sandybarasker · Sep 24, 2012 · Viewed 15.7k times · Source

how to insert or append new line on top of the jtextarea in java swing ? i want to to append jtextarea and add the new line on top of the jtextarea please help me how to do this.

Answer

Dan D. picture Dan D. · Sep 24, 2012

You can do this:

textArea.setText("The new text\n" + textArea.getText());

Or, an even better solution would be this:

try {
  textArea.getDocument().insertString(0, "The new text\n", null);
} catch (BadLocationException e) {
  e.printStackTrace();
}