Search code examples
javaswingawtjscrollpanejtextarea

JTextArea scroll to bottom only if text is appended


I am trying to create a JTextArea which scrolls to bottom every time a text is appended to that text area. Otherwise, the user should be able to scroll top and see previous message. I used this code:

JTextArea terminalText  = new JTextArea();
JPanel terminal = new JPanel();
terminal.setLayout(new BorderLayout()); 
add(terminal);  //Adds the terminal to mother JPanel

//I added scrollbar to my JTextArea
JScrollPane scroll = new JScrollPane(terminalText);  
terminal.add(scroll, BorderLayout.CENTER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

scroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
public void adjustmentValueChanged(AdjustmentEvent e) {  
 e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
}});

So far this code seems to make my text area scroll to bottom of the terminalText text area every time I append something to terminalText using terminalText.append.

However, the user cannot use scroll bar to scroll to the top to see previous message. Is there a way to fix this? Should I be using DocumentListener to achieve this?


Solution

  • Check out Smart Scrolling.

    If the scrollbar is at the bottom, then as text is appended you will see the new text.

    If the user has scrolled to a different position, then the viewport will stay there until the user scrolls back to the bottom.