Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll down automatically JTextArea for show the last lines added

I have written a Java application that receives information from a server every 10 seconds. I am wanting to display this information on a form.

Currently I am using a JTextArea. However, once the JTextArea is filled up, I cannot see the new information that is added to this JTextArea. Do I need to add scroll bars to the JTextArea? Or is there a completely new different control for GUI forms that is recommended to display information that is added every x seconds?

like image 858
user2381256 Avatar asked May 18 '13 05:05

user2381256


2 Answers

DefaultCaret tries to make itself visible which may lead to scrolling of a text component within JScrollPane. The default caret behavior can be changed by the DefaultCaret#setUpdatePolicy method.

Assumption that the name of your variable is textArea, you only need to modify the policy of caret:

DefaultCaret caret = (DefaultCaret) textArea.getCaret(); // ←
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);       // ←
...
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(textArea);

* Thanks, mKorbel

like image 85
Paul Vargas Avatar answered Oct 07 '22 14:10

Paul Vargas


Do I need to add scroll bars to the JTextArea?

Add the text area to a JScrollPane. See How to Use Scroll Panes for more information & examples.

Here is an example:

Text Area - Scrollable

import java.awt.*;
import java.io.*;
import javax.swing.*;

class TextAreaScrolling {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                final JTextArea out = 
                        new JTextArea(5,10); // suggest columns & rows
                JScrollPane outScroll = new JScrollPane(out);

                File f = new File("TextAreaScrolling.java");
                try {
                    Reader reader = new FileReader(f);
                    out.read(reader, f);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                JOptionPane.showMessageDialog(null, outScroll);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
like image 40
Andrew Thompson Avatar answered Oct 07 '22 13:10

Andrew Thompson