如何限制JTextArea的最大行数和列数?

6

我正在使用JScrollPane中的JTextArea。

我想限制可能的最大行数和每行的最大字符数。

我需要字符串在屏幕上完全像样,每行都以“\n”结尾(如果有另一行在其后),并且用户只能插入X行和Y个字符。

我尝试限制行数,但由于换行,我不知道有多少行。换行是在视觉上开始新的一行(因为JTextArea的宽度),但在组件的字符串中,它确实是没有“\n”来表示新行的同一行。我不知道如何在输入时限制每行的最大字符数。

有两个阶段:

  1. 字符串的输入 - 保持用户无法在每行中键入超过X行和Y个字符(即使换行符仅在视觉上或用户键入了“/n”)。
  2. 将字符串插入到数据库中 - 单击“确定”后,将字符串转换为每行都以“/n”结尾,即使用户没有在行末键入它,该行仅在视觉上被包装。

如果我计算行中的字符并在行末插入“/n”,那么就会出现几个问题,这就是为什么我决定分两个阶段进行的原因。在用户输入时,我宁愿只在视觉上限制它并强制进行换行或类似的操作。只有在第二阶段保存字符串时,即使用户没有在行末键入它,我也会在每行末尾添加“/n”!

有人有想法吗?


我知道我必须使用DocumentFilter或StyledDocument。

这是一个仅将行限制为3个(但不限制行中的字符数)的示例代码:

private JTextArea textArea ;
textArea  = new JTextArea(3,19);
textArea  .setLineWrap(true);
textArea .setDocument(new LimitedStyledDocument(3));
JScrollPane scrollPane  = new JScrollPane(textArea

public class LimitedStyledDocument extends DefaultStyledDocument

    /** Field maxCharacters */
    int maxLines;

    public LimitedStyledDocument(int maxLines) {
        maxCharacters = maxLines;
    }

public void insertString(int offs, String str, AttributeSet attribute) throws BadLocationException {
    Element root = this.getDefaultRootElement();
    int lineCount = getLineCount(str);

    if (lineCount + root.getElementCount() <= maxLines){
        super.insertString(offs, str, attribute);
    }
    else {
        Toolkit.getDefaultToolkit().beep();
    }
}

 /**
 * get Line Count
 * 
 * @param str
 * @return the count of '\n' in the String
 */
private int getLineCount(String str){
    String tempStr = new String(str);
    int index;
    int lineCount = 0;

    while (tempStr.length() > 0){
        index = tempStr.indexOf("\n");
        if(index != -1){
        lineCount++;
            tempStr = tempStr.substring(index+1);
        }
    else{
        break;
        }
    }
    return lineCount;
   }
}

不是答案,但你最好使用文档过滤器。 - Tom Hawtin - tackline
2个回答

1

这是我的版本,基于Nick Holt的版本。

仅供记录,这将用于原型,并没有经过太多测试(如果有的话)。

public class LimitedLinesDocument extends DefaultStyledDocument {
    private static final long serialVersionUID = 1L;

    private static final String EOL = "\n";

    private final int maxLines;
    private final int maxChars;

    public LimitedLinesDocument(int maxLines, int maxChars) {
        this.maxLines = maxLines;
        this.maxChars = maxChars;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet attribute) throws BadLocationException {
        boolean ok = true;

        String currentText = getText(0, getLength());

        // check max lines
        if (str.contains(EOL)) {
            if (occurs(currentText, EOL) >= maxLines - 1) {
                ok = false;
            }
        } else {
            // check max chars
            String[] lines = currentText.split("\n");
            int lineBeginPos = 0;
            for (int lineNum = 0; lineNum < lines.length; lineNum++) {
                int lineLength = lines[lineNum].length();
                int lineEndPos = lineBeginPos + lineLength;

                System.out.println(lineBeginPos + "    " + lineEndPos + "    " + lineLength + "    " + offs);

                if (lineBeginPos <= offs && offs <= lineEndPos) {
                    System.out.println("Found line");
                    if (lineLength + 1 > maxChars) {
                        ok = false;
                        break;
                    }
                }
                lineBeginPos = lineEndPos;
                lineBeginPos++; // for \n
            }
        }

        if (ok)
            super.insertString(offs, str, attribute);
    }

    public int occurs(String str, String subStr) {
        int occurrences = 0;
        int fromIndex = 0;

        while (fromIndex > -1) {
            fromIndex = str.indexOf(subStr, occurrences == 0 ? fromIndex : fromIndex + subStr.length());
            if (fromIndex > -1) {
                occurrences++;
            }
        }

        return occurrences;
    }
}

1

以下方法对我有效:

public class LimitedLinesDocument extends DefaultStyledDocument 
{    
  private static final String EOL = "\n";

  private int maxLines;

  public LimitedLinesDocument(int maxLines) 
  {    
    this.maxLines = maxLines;
  }

  public void insertString(int offs, String str, AttributeSet attribute) throws BadLocationException 
  {        
    if (!EOL.equals(str) || StringUtils.occurs(getText(0, getLength()), EOL) < maxLines - 1) 
    {    
      super.insertString(offs, str, attribute);
    }
  }
}

StringUtils.occurs 方法的定义如下:

public static int occurs(String str, String subStr) 
{    
  int occurrences = 0;
  int fromIndex = 0;

  while (fromIndex > -1) 
  {    
    fromIndex = str.indexOf(subStr, occurrences == 0 ? fromIndex : fromIndex + subStr.length());
    if (fromIndex > -1) 
    {    
      occurrences++;
    }
  }

  return occurrences;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接