I have a JTextArea wrapped in a JScrollPane, which I use to log my application's output. As the application produces many lines, the number of lines in the text area is growing really fast and the scroll becomes nearly invisible. I'd like to have a text area like the Eclipse console.. I mean.. a text area with a vertical scroll but when using the scroll I can only show at maximum the latest 200 rows.
Here is the runnable code I'm using:
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
public class WindowLog extends JFrame {;
private JPanel contentPane;
private static JTextArea textArea = new JTextArea();
public static void run() {
try {
WindowLog frame = new WindowLog();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeText(JTextArea ta, String s){
DefaultCaret caret = (DefaultCaret)ta.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
ta.append(s);
}
/**
* Create the panel.
*/
public WindowLog() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 523, 299);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.setLayout(null);
JLabel lblLog = new JLabel("Log");
lblLog.setBounds(5, 5, 497, 14);
getContentPane().add(lblLog);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 30, 492, 138);
//scrollPane.getViewport().setPreferredSize(new Dimension(300, 100));
textArea.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
contentPane.add(scrollPane);
scrollPane.setViewportView(textArea);
Main.setTextProva(textArea);
}
}
and here is Main class:
public class Main {
static JTextArea textProva;
public static void setTextProva(JTextArea textProva) {
Main.textProva = textProva;
}
public static void main(String[] args) {
WindowLog.run();
System.out.println(textProva);
WindowLog.writeText(textProva, "hello"+"\n");
}
Thanks in advance.
Add a DocumentFilter to the document of the text area. In the filter check how many rows are there. If the max count is achieved remove previous content from the text area.