Reputation: 670
I want to use jTextArea as log of events for my application. I know I can redirect system.out and system.in but I want to use multiple jTextArea logs for different parts of my code. For example I want to do TCPServer log and display log for it in jTextArea. For example it should have some data like this.
2015-01-01 12:00:00 - TCPServer started listening on port 10000
2015-01-01 12:05:00 - Client with IP 192.168.0.1 connected
2015-01-01 12:06:00 - Client with IP 192.168.0.2 connected
2015-01-01 12:05:00 - Client with IP 192.168.0.1 send "Hello server" message
2015-01-01 12:05:00 - Client with IP 192.168.0.1 disconnected
What I want to show is the last X lines, maybe 100 lines as a limit. The older lines should not be displayed. I know when I add the 101 line I can read all of the lines by splitting all the text from the jTextArea by \n and filling it again with Strings from 2 to 101, but I am looking for better and more efficient solution.
In the past I think I found some document listener that do this, but the last 3 days I couldn't find it. Maybe I am searching it wrong now or asking bad for my problem.
Upvotes: 3
Views: 562
Reputation: 245
I think this is the listener that you are talking about:
https://tips4java.wordpress.com/2008/10/15/limit-lines-in-document/
It's simple to use:
textComponent.getDocument().addDocumentListener(
new LimitLinesDocumentListener(50) );
Upvotes: 3
Reputation: 17945
Keep an ArrayDeque<Integer>
to store the lengths of the lines that you print to your JTextArea: each time you insert a line, if there are less than N (= whatever your intended maximum) lines, just append it to the end of your queue. If there are already N lines, then use
myTextArea.replaceRange("", 0, myQueue.remove());
This replaces the first line by nothing, effectively removing it.
To add a new line, use
myQueue.addLast(textToAdd.length()); // maybe +1 to account for endline?
myTextArea.append(textToAdd); // may require a "/n"?
This would be much more efficient than your current implementation.
Upvotes: 1