我在 JScrollPane 中使用 JTextArea
我想限制可能的最大行数和每行的最大字符数。
我需要该字符串与屏幕上的完全相同,每行将以 '\n' 结尾(如果后面还有另一行),并且用户将能够在每行中仅插入 X 行和 Y 字符。
我试图限制行数,但由于换行,我不知道到底有多少行,换行是在屏幕上可视地开始新行(因为 JTextArea 的宽度),但在字符串中该组件实际上是同一行,没有 '\n' 来指示新行。我不知道如何在打字时限制每行的最大字符数。
有 2 个阶段:
- 字符串的键入 - 请注意用户将无法键入超过 X 行和每行中的 Y 个字符。 (即使换行仅在视觉上或用户键入“/n”)
- 将字符串插入数据库 - 单击“确定”后,将字符串转换为每行都以“/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;
}
}
以下对我有用:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)