Search code examples
javalinelimitjtextarea

JTextArea show last X lines


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.


Solution

  • 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) );