如何限制JTextArea中的行数? [英] How to Limit number of lines in JTextArea?

查看:426
本文介绍了如何限制JTextArea中的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为服务创建一个GUI,该GUI具有一个JTextArea来查看消息,每条消息都写在一行上,并在需要时进行自动换行.

I am trying to make a GUI for a service, which have a JTextArea to view messages in, each message is written on a single line, and wordwrapped if needed.

消息是通过套接字到达的,所以我只是用来更新JTextArea的.append(message),我需要将这些行限制为50或100,并且我不需要限制每行的字符数线.

The messages arrive via a socket, so it is merely an .append(message) that i am using to update the JTextArea, i need to limit these lines to 50 or 100 and i have no need to limit character count on each line.

如果有一种方法可以限制JTextArea中的行数,或者有另一种方法可以做到这一点?

If there is a method to limit the number lines in the JTextArea or if there is an alternative method of doing it?

在这件事上我真的可以使用帮助.

I could really use the assistance in this matter.

修改

问题在于每个客户端都可以发送无限行,所有这些行都必须可读,因此这不是对JTextArea中行数的简单检查.我需要删除较旧的行才能查看较新的行.

The problem is that each client can send infinite lines, all these lines have to be readable, so this is not a simple check of the number of lines in the JTextArea. I need to remove older lines in order to view newer lines.

推荐答案

这样会更有效吗?

final int SCROLL_BUFFER_SIZE = 100;
public void trunkTextArea(JTextArea txtWin)
{
    int numLinesToTrunk = txtWin.getLineCount() - SCROLL_BUFFER_SIZE;
    if(numLinesToTrunk > 0)
    {
        try
        {
            int posOfLastLineToTrunk = txtWin.getLineEndOffset(numLinesToTrunk - 1);
            txtWin.replaceRange("",0,posOfLastLineToTrunk);
        }
        catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }
}

这篇关于如何限制JTextArea中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆