Java Swing: Auto-Scrolling JScrollPane (i.e. Chat Window)

This is just a short tutorial on how to make an auto scrolling pane in Java Swing. I was doing a chat client not too long ago, so I figured I’d assemble this short Swing tutorial for those interested in this particular behavior. This uses a JTextArea and a JScrollPane. I commented most of the lines, but I invite you to refer to the Java API for methods you don’t fully understand. Feel free to ask questions or suggest improvements in the comments section! Click here for the code.

Auto-Scrolling JTextArea/JScrollPane

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Demo extends JFrame{
    public Demo() {
        super("Auto-Scroll JTextArea");
        
        // We create a TextArea object
        final JTextArea textArea = new JTextArea(5, 30);
        // We put the TextArea object in a Scrollable Pane
        JScrollPane scrollPane = new JScrollPane(textArea);
    
        // In order to ensure the scroll Pane object appears in your window, 
        // set a preferred size to it!
        scrollPane.setPreferredSize(new Dimension(380, 100));
    
        // Lines will be wrapped if they are too long to fit within the 
        // allocated width
        textArea.setLineWrap(true);
    
        // Lines will be wrapped at word boundaries (whitespace) if they are 
        // too long to fit within the allocated width
        textArea.setWrapStyleWord(true);
    
        // Assuming this is the chat client's window where we read text sent out 
        // and received, we don't want our Text Area to be editable!
        textArea.setEditable(false);
    
        // We also want a vertical scroll bar on our pane, as text is added to it
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    
        // Now let's just add a Text Field for user input, and make sure our 
        // text area stays on the last line as subsequent lines are 
        // added and auto-scrolls
        final JTextField userInputField = new JTextField(30);
        userInputField.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                //We get the text from the textfield
                String fromUser = userInputField.getText();
    
                if (fromUser != null) {
                    //We append the text from the user
                    textArea.append("Asim: " + fromUser + "\n");
        
                    //The pane auto-scrolls with each new response added
                    textArea.setCaretPosition(textArea.getDocument().getLength());
                    //We reset our text field to "" each time the user presses Enter
                    userInputField.setText("");
                }
            }
        });

        this.setLayout(new FlowLayout());
        //adds and centers the text field to the frame
        this.add(userInputField, SwingConstants.CENTER);
        //adds and centers the scroll pane to the frame
        this.add(scrollPane, SwingConstants.CENTER);
        
        // Set size, default close operation, resizability boolean and overall contents visibility
        this.setSize(400, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        //That's it for now!
        new Demo();
    }
}

Update (06/27/2016): Refactored code to support Java 1.8 (Update 91).

  • chuck51

    thanks for the code but on my computer there is only the jframe window displayed and nothing inside :/

    (windows 10 and last java jdk and last eclipse running)

    • Hey Chuck!
      I downloaded the latest Eclipse (Neon) and the latest JDK (v1.8.91 or 1.8 Update 91). Like you said, the JFrame window displayed and there was nothing inside.
      I refactored the code a bit (moved the function call that sets the visibility of the inner contents of the JFrame).
      It should be working for you now!

      Cheers,
      Cyrille

      • chuck51

        Thanks dude for fixing the code after so much time, that’s very kind of you! Everything works fine on my computer 🙂

  • Dude

    My error is , that i cant resolve scrollpane as a type 🙁

    • Are you calling the correct import statement?

      import javax.swing.JScrollPane;

  • rushi

    thank you..awesome work..great help

    • You’re welcome!

  • jpopper

    you are awesome. make my say

    • jpopper

      day xd