JTextArea显示最后X行

时间:2015-03-05 11:48:13

标签: java line limit jtextarea

我想使用jTextArea作为我的应用程序的事件日志。我知道我可以重定向system.out和system.in但我想为我的代码的不同部分使用多个jTextArea日志。例如,我想在jTextArea中执行TCPServer日志并显示日志。例如,它应该有这样的数据。

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

我想要显示的是最后的X行,可能是100行作为限制。不应显示旧行。我知道当我添加101行时,我可以读取所有行,方法是将所有文本从jTextArea中除去\ n并再次使用2到101的字符串填充它,但我正在寻找更好,更有效的解决方案。

过去我认为我找到了一些文件监听器来做到这一点,但过去3天我找不​​到它。也许我现在正在寻找错误或者对我的问题不好。

2 个答案:

答案 0 :(得分:3)

我认为这是你所说的聆听者:

https://tips4java.wordpress.com/2008/10/15/limit-lines-in-document/

使用简单:

textComponent.getDocument().addDocumentListener(
    new LimitLinesDocumentListener(50) );

答案 1 :(得分:1)

保持ArrayDeque<Integer>以存储您打印到JTextArea的行的长度:每次插入一行时,如果小于N(=无论您的预期最大值)行,只需将其附加到你的队列结束了。如果已有N行,则使用

myTextArea.replaceRange("", 0, myQueue.remove()); 

这将取消第一行,实际上将其删除。

要添加新行,请使用

myQueue.addLast(textToAdd.length()); // maybe +1 to account for endline?
myTextArea.append(textToAdd);        // may require a "/n"?

这比您当前的实施效率更高。