JScrollPaneでJTextAreaを使用しています
可能な最大行数と各行の最大文字数を制限したいと思います。
文字列が画面とまったく同じで、各行が「\ n」で終わり(その後に別の行がある場合)、ユーザーは各行にX行とY文字のみを挿入できるようにする必要があります。
行を制限しようとしましたが、行の折り返しのために行数が正確にわかりません。行の折り返しは、画面上で視覚的に新しい行を開始しています(JTextAreaの幅のため)が、コンポーネントそれは実際には同じ行であり、新しい行を示す'\n'はありません。入力中に各行の最大文字数を制限する方法がわかりません。
2つの段階があります:
- 文字列の入力-ユーザーが各行にX行とY文字を超えて入力できないようにします。(行が視覚的にのみ折り返されている場合や、ユーザーが「/ n」と入力した場合でも)
- 文字列をDBに挿入します-「OK」をクリックした後、ユーザーが入力せず、行が視覚的にのみ折り返されている場合でも、すべての行が「/n」で終わる文字列を変換します。
行の文字数を数え、行の最後に「/ n」を挿入する場合、問題はほとんどありません。そのため、2段階で行うことにしました。最初の段階では、ユーザーが入力しているときに、視覚的に制限するだけで、ラインのワーピングなどを強制します。文字列を保存する第2段階でのみ、ユーザーが行の最後に入力しなくても「/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;
}
}