Java Swing How to - Add Auto-scroll when text is added to my JScrollPane/JTextArea








Question

We would like to know how to add Auto-scroll when text is added to my JScrollPane/JTextArea.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/* w  ww .  j a v  a  2 s  . c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame {
  JTextArea txtMain;

  Main() {
    setSize(500, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    JScrollPane pane = new JScrollPane();
    txtMain = new JTextArea();
    pane.setViewportView(txtMain);
    this.add(pane, BorderLayout.CENTER);

    JButton btnAddText = new JButton("Add Text");
    btnAddText
        .addActionListener(e -> {
          txtMain.setText(txtMain.getText()
              + "\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis id nibh vel rhoncus. ");
          String text = txtMain.getText();
          txtMain.setCaretPosition(text != null ? text.length() : 0);
        });
    add(btnAddText, BorderLayout.SOUTH);
    setVisible(true);
  }
  public static void main(String[] args) {
    new Main();
  }
}