Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JTextArea显示最后的X行_Java_Line_Limit_Jtextarea - Fatal编程技术网

Java JTextArea显示最后的X行

Java JTextArea显示最后的X行,java,line,limit,jtextarea,Java,Line,Limit,Jtextarea,我想使用jTextArea作为我的应用程序的事件日志。我知道我可以重定向system.out和system.in,但我想对代码的不同部分使用多个jTextArea日志。例如,我想做TCPServer日志并在jTextArea中显示它的日志。例如,它应该有一些这样的数据 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 co

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

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天里,我找不到它。也许我现在找错了,或者问错了我的问题

保留一个
ArrayDeque
以存储打印到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"?

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

我认为这就是您正在谈论的侦听器:

使用起来很简单:

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

我想我使用的是同一个文档监听器,谢谢你,我仍然不知道为什么我在谷歌上找不到它。