2010-05-07 9 views
8
DocumentListener dl = new MessageDocumentListener(); 
((AbstractDocument) nboxArea.getDocument()).setDocumentFilter(new DocumentFilter() { 
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { 
     string = string.replaceAll("\t", ""); 
     super.insertString(fb, offset, string,(javax.swing.text.AttributeSet) attr); 
    } 

    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { 
     text = text.replaceAll("\t", ""); 
     //TODO must do something here 
     super.replace(fb, offset, length, text,(javax.swing.text.AttributeSet) attrs); 
    } 
}); 

JTextArea evArea = (JTextArea) c; 
evArea.getDocument().removeDocumentListener(dl); 
evArea.setText(originalMessage); 

En este caso encontré el siguiente error durante la configuración del texto en textarea. No sé cómo resolverlo.java.lang.IllegalStateException durante el uso de Document Listener en TextArea, Java

Exception in thread "AWT-EventQueue-0" 
java.lang.IllegalStateException: Attempt to mutate in notification 

Creo que el problema es establecer el texto en el documento o documento de configuración en el detector de documentos. Pero no sé cómo resolver esto. Porfavor ayudame a resolver este problema.

Respuesta

9

No puede modificar el documento dentro de DocumentListener. Escriba un documento personalizado en su lugar, que anula los métodos insertString() o remove().

De Tutoriales de Java: How to write a DocumentListener

oyentes documento no debe modificar el contenido del documento; El cambio ya está completo para cuando se le notifica al oyente el cambio. En su lugar, escriba un documento personalizado que anule los métodos insertString o remove, o ambos. Vea Listening for Changes on a Document para más detalles.

3

Si quiere mutar en el oyente, puede iniciar un hilo por separado para hacerlo más tarde con SwingUtilities.invokeLater. Tenga cuidado porque las modificaciones del subproceso independiente volverán a llamar al oyente, por lo tanto, establezca un booleano antes de iniciar el subproceso, regrese inmediatamente del oyente si se establece y reinícielo después de que las modificaciones se hayan realizado en el subproceso separado.

Cuestiones relacionadas