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?
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
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:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With