Before I make my suggestion, let me offer this caveat: I write mostly back-end code
and web applications. I have never before worked with Swing.
With that said, though, I think I can offer an easy solution that will let the garbage
collector do the work of keeping your memory usage down. This solution simply extends
JTextArea and overrides append(String) with something that monitors length on your
behalf.
If you were doing this in a more permanent fashion or if you knew you would later want
to use this same concept on other subclasses of JTextComponent, you would be better to
do this as a separate object (instead of a subclass). You could then have that object
register for events with the JTextArea and then trim off the excess text as needed.
Anyhow, this idea is quick and probably works for what you need. Here's the idea:
-----------------------------------
public class MaxLengthTextArea
extends javax.swing.JTextArea
{
private int maxTextLength = 0;
public MaxLengthTextArea(int maxLength) {
this.maxTextLength = maxLength;
}
/**
* This overrides javax.swing.JTextArea.append(String) so that
* it never has more than this.maxTextLength worth of characters.
*/
public void append(String str)
{
if (str == null) {
return;
} else if (str.length() > this.maxTextLength) {
throw new java.lang.IndexOutOfBoundsException("The string that
is to be appended is longer than the maximum length allowed.");
} else {
// Figure out how much larger or smaller than the max the new
// string would be.
int delta = (this.getText().length() + str.length()) -
this.maxTextLength;
// If it would be larger than the max, then delete some from
// the beginning of the string.
if (delta >= 0) {
this.replaceRange(null, 0, delta);
}
// Now that everything is trimmed down to size, use the parent
// class's definition for append(String)
super.append(str);
}
}
}
-----------------------------------
_______________________________________________
Juglist mailing list
[EMAIL PROTECTED]
http://trijug.org/mailman/listinfo/juglist_trijug.org