6

我在 JScrollPane 中使用 JTextArea

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

我需要字符串与屏幕上的完全一样,每一行都以 '\n' 结尾(如果后面有另一行),用户将只能在每行中插入 X 行和 Y 字符。

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

有2个阶段:

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

如果我将计算行中的字符并在行尾插入'/n',则几乎没有问题,这就是我决定分两个阶段进行的原因。在第一阶段,用户正在打字,我宁愿只在视觉上限制它并强制换行或类似的东西。只有在第二阶段,当我保存字符串时,我才会添加“/n”,即使用户没有在行尾键入它!

有人有想法吗?


我知道我将不得不使用 DocumentFilter 或 StyledDocument。

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

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;
   }
}
4

2 回答 2

1

这是我的版本,基于尼克霍尔特的版本。

只是为了记录,这将在原型中使用,并且没有经过太多测试(如果有的话)。

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;
    }
}
于 2010-03-18T03:09:58.790 回答
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;
}
于 2009-09-30T09:55:23.277 回答