Bil*_*bug 6 java text lines limit jtextarea
我在 JScrollPane 中使用 JTextArea
我想限制可能的最大行数和每行中的最大字符数。
我需要字符串与屏幕上的完全一样,每一行都以 '\n' 结尾(如果后面还有另一行),并且用户将只能在每行中插入 X 行和 Y 字符。
我试图限制行,但由于换行,我不知道到底有多少行,换行是在屏幕上直观地开始新行(因为 JTextArea 的宽度),但在字符串中组件实际上是同一行,没有 '\n' 表示新行。我不知道如何在打字时限制每行中的最大字符数。
有2个阶段:
如果我计算行中的字符数并在行尾插入 '/n' 几乎没有问题,这就是我决定分两个阶段进行的原因。在第一阶段 ehile 用户正在输入我宁愿只限制它的视觉和强制换行或类似的东西。只有在第二阶段,当我保存字符串时,我才会添加 '/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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下对我有用:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
其中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;
}
Run Code Online (Sandbox Code Playgroud)