The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

try this --- setDocument() ... Document class - insertString(...) method

Posted by ping203 on February 08, 2002 at 10:13 AM

You can set the document of the JTextArea, and then override the insertString method. Each time you insert something to the text area, the insertString method is called to do the insertion. So, you can do a test before in this method.

I did not test the following codes, but that is the idea. Also, if you do a copy & paste, if the result is > limit, it just returns. If you want to paste partial string up to the limit, then you need to do some substring copy.

try this
JtextArea1.setDocument(new MaxSizeDocument() extends PlainDocument
{
public void insertString(int offset, String string,
AttributeSet attributes)
throws BadLocationException {
if (string == null) {
return;
} else {
int textArealength = getLength();
int newStringLength = string.length();
if (MAX_SIZE < (textArealength + newStringLength))
return; //reach limit
String newValue;
if (textAreaLength == 0)
newValue = string;
else {
String currentContent = getText(0, textAreaLength);
StringBuffer currentBuffer = new StringBuffer(currentContent);
currentBuffer.insert(offset, string);
newValue = currentBuffer.toString();
}
super.insertString(offset, string, attributes);
}
}//end method
});






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us