Originariamente inviato da Paoletta_r
Ora mi da questo errore....
Exception in thread "main" java.lang.IllegalArgumentException: Model must be StyledDocument
at javax.swing.JTextPane.setDocument(Unknown Source)
at jcshell.gui.Gui.<init>(Gui.java:152)
at jcshell.gui.Main.main(Main.java:15)
Sono riuscita a fare un sacco di cose strane con java ma questo document proprio non ne vuole sapere...
Si scusa ho sbagliato io... il codice che avevo postato non andava bene per JTextPane
(ho modifcato il mio post precedente
)
Credo di aver risolto. Ho utilizzato l'esempio DocumentSizeFilter della sun ed è bastato ridefinire il metodo remove:
codice:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class DocumentSizeFilter extends DocumentFilter {
int maxCharacters;
boolean DEBUG = false;
public DocumentSizeFilter(int maxChars) {
maxCharacters = maxChars;
}
public void remove (FilterBypass fb, int offs,int len){
return ;
}
public void insertString(FilterBypass fb, int offs,
String str, AttributeSet a)
throws BadLocationException {
if (DEBUG) {
System.out.println("in DocumentSizeFilter's insertString method");
}
//This rejects the entire insertion if it would make
//the contents too long. Another option would be
//to truncate the inserted string so the contents
//would be exactly maxCharacters in length.
if ((fb.getDocument().getLength() + str.length()) <= maxCharacters){
super.insertString(fb, offs, str, a);
}
else
Toolkit.getDefaultToolkit().beep();
}
public void replace(FilterBypass fb, int offs,
int length,
String str, AttributeSet a)
throws BadLocationException {
if (DEBUG) {
System.out.println("in DocumentSizeFilter's replace method");
}
//This rejects the entire replacement if it would make
//the contents too long. Another option would be
//to truncate the replacement string so the contents
//would be exactly maxCharacters in length.
if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters){
super.replace(fb, offs, length, str, a);
}
else
Toolkit.getDefaultToolkit().beep();
}
}
e per settare il filtro:
codice:
StyledDocument styledDoc = tp.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
AbstractDocument doc = (AbstractDocument)styledDoc;
doc.setDocumentFilter(new DocumentSizeFilter(5));
}