If I want to prevent the JTextArea from scrolling to the bottom when I add text to the end, the solution is very simple: Just set the caret's update policy to DefaultCaret.NEVER_UPDATE before calling the JTextArea's append method. I am trying to do the same thing (load the text without scrolling), but for prepending text instead of appending text.
I have tried lots of things. One of them is this, but it doesn't work:
public void loadMoreUp(){
caret = (DefaultCaret)ta.getCaret(); // ta is a JTextArea
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); //doesn't work
String s = "The new text\n";
ta.setText(s + ta.getText()); // I have also tried with ta.getDocument().insertString(0,s,null)
}
The behavior I want is that "The new text" gets prepended to the top, but the JTextArea doesn't scroll up with it. "The new text" should not be visible unless the user manually scrolls up to see it.
How can I prepend text to the top of a JTextArea, without it scrolling up? My JTextArea is in a JScrollPane if that is relevant.
textArea.insert("Mein Hund frisst Nuesse\n", 0);textArea.setText("Mein Hund frisst Nuesse\n" + textArea.getText());I tried to repro by typing letters followed by <enter> until I passed the size of the textArea and got the scrollbars to show. Then I clicked a button that ran that code and the viewport stayed, showing the last letters I typed. To see the prepended text, I had to manually scroll up. - MarsAtomic