JTextArea DocumentListener throwing 'Attempt to mutate in notification'

I'm trying to limit the number of characters input into a JTextArea. At the moment I've attached a DocumentListener to it and am acting on the length of the JTextArea. I understand why it's kicking me out, being too recursive, so I'm guessing my method is totally wrong. I searched on the forum and someone mentioned passing a Document argument to JTextArea on initialisation, but I couldn't find any more details on how to do it. Can anyone help?
Thanks

A newer approach (as of 1.4, I believe) is to use a DocumentFilter and this exact example is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.

Similar Messages

  • Attempt to mutate in notification error

    I have a text editor, i want to make this
    when i man type double /, che color of the text from position 0 to position 10 become blue
    I write code like this
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    public class TextComponentDemo extends JFrame {
    JTextPane textPane;
    DefaultStyledDocument dsd;
    Hashtable actions;
    SimpleAttributeSet attrs;
    Style style;
    public TextComponentDemo() {
    //Create the document for the text area.
    dsd = new DefaultStyledDocument();
    //Create the text pane and configure it.
    textPane = new JTextPane(dsd);
    attrs = new SimpleAttributeSet();
    StyleConstants.setForeground(attrs, Color.blue);
    dsd.addDocumentListener(new MyDocumentListener());
    //And this one listens for any changes to the document.
    protected class MyDocumentListener
    implements DocumentListener, ChangeListener {
    public void insertUpdate(DocumentEvent e) {
         if (sel.compareTo("//") == 0) {
         dsd.setCharacterAttributes(0,10, attrs, true);
    but i have this exception at line
    dsd.setCharacterAttributes(0,10, attrs, true);
    Can't take the textjava.lang.IllegalStateException: Attempt to mutate in notification
    how i can resolve this exception?

    thx
    you know where i can file an example that when i press
    the program show a windows with the list of java method, like this
    JFrame jf = new JFrame();
    jf.
    setSize()
    setBound()
    setTitle()
    getPosition()
    ecc...

  • Java.lang.IllegalStateException: Attempt to mutate in notification

    I get this exception sometimes when I change a value in a row of a JTable in a JClient. But I don't understand when the exception is called.
    Can somebody explain me what this exception means and how to avoid this??
    The next lines are from the stack-output and I think the problem has something to do with one of my methode-call "setDetailTyp()") but I don't know why??
    de.rac.codesDB.Client.MDPanelMWBKapitel.setDetailTyp(MDPanelMWBKapitel.java:72)
    de.rac.codesDB.Client.MDPanelMWBKapitel.insertUpdate(MDPanelMWBKapitel.java:197)

    i figured out the problem

  • Unity Connection 10 - EventID: 0xC0000007 (7) - After 5 unsuccessful attempts to send a notification for subscription

    hello,
    i am receiving this event on MX:
    this is showing ip address of my unity connection that is 172.20.101.22....
    what could be reason and cause of it?
    EventID: 0xC0000007 (7) - After 5 unsuccessful attempts to send a notification for subscription [EABtYngwMi5uaGljLmxvY2FsEAAAAIfIUmalt2VFie2S8ahJiKNZu5GtCIfRCA==] against endpoint [http://172.20.101.22:7080/NotificationService/services/NotificationService?id=33a00cf5-3f28-44e1-9d44-46b24da4bc2a&pid=14227], the subscription has been removed. Details: WebException: Unable to connect to the remote server Status: ConnectFailure at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
    at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)
    at Microsoft.Exchange.Services.Core.NotificationServiceClient.CreateSendNotificationRequestAsync(IAsyncResult requestAsyncResult)

    Navigate to CUC Administration, set the following under SMTP Configuration > Server, and give it another shot.
    [V] Allow Connections From Untrusted IP Addresses
      [ ] Require Authentication From Untrusted IP Addresses
    -Mateusz

  • Trying to amend textArea

    I have a textArea(attached is a document listenter and a CaretListener) where I am trying to amend the contents. What I am trying to accomplish is when a user inputs text into the textArea that he/she cannot enter text past a certain point (ie caret postion 200). Also, if the text that gets inserted causes the text to go longer than caret position 200, then the text gets cut off.
    The problem is I get the following error when I try and replace or set the textArea.
    (java.lang.IllegalStateException: Attempt to mutate in notification)
    Yet I have another program where the same thing works fine in an actionListener. I do not understand why I can not get it to work in the document listener. The textArea gets locked for some reason and I can not ammend it. I f someone can help me that would be nice of you.
    java.lang.IllegalStateException: Attempt to mutate in notification
    public void setCursor()
    if(textArea.getCaretPosition() >= 200)
    textArea.setCaretPosition(200);
    public void delText()
    if(textArea.getText().length() > 200)
    String area = textArea.getText().substring(0, 199);
    textArea.setText(" ");
    textArea.replaceRange(area, 0 , 199); /* java.lang.IllegalStateException: Attempt to mutate in
    notification */
    class TextDocListener implements DocumentListener
    public void insertUpdate(DocumentEvent e) {delText();}
    public void removeUpdate(DocumentEvent e) {}
    public void changedUpdate(DocumentEvent e) {}
    class TextCaretListener implements CaretListener
    public void caretUpdate(CaretEvent e) { setCursor(); }

    Hi!
    Subclass javax.swing.text.PlainDocument
    then:
    public void insertString(int offset, String newString, javax.swing.text.AttributeSet set) throws javax.swing.text.BadLocationException
               String s = this.getContent()+newString;
               if(s.length()<200)
                       super.insertString(offset, newString, set);
                else
                   int cap = 200-this.getContent().length();
                   if(cap>0)
                          String ins = newString.subString(0, cap);
                          super.insertString(offset, ins, set);
    }Finally, when creating the TextArea call:
    myTextArea.setDocument(myPlainDocument);:)

  • Manage inserts in a JTextField

    First, happy new years to all java developpers.
    Secondly, place to my problem ;)
    I would like to manage the inserts into a JTextField, for exemple (and only for example) , The user won't be able to insert the caracter 'a' in the JTextField.
    So, I have created a class who implements DocumentListener, this document listener will be associated to a JTextField component :
    public class EcouteDocument implements DocumentListener {
    public EcouteDocument() {
    public void insertUpdate(DocumentEvent e) {
    try{
    if (e.getDocument().getText(0,1).compareTo("a") == 0){
    System.out.println("a inserted");
    e.getDocument().remove(0,1);
    catch(Exception ex){
    ex.printStackTrace();
    public void removeUpdate(DocumentEvent e) { }
    public void changedUpdate(DocumentEvent e) {}
    The user can't insert 'a', so when it's done, I remove the caracter, but I have this exception :
    java.lang.IllegalStateException: Attempt to mutate in notification
    I'm sure that's not the good solution but I can't find an other. Can you help me please ? To start a good year ? ;)
    Thanks...
    A newbie in a world of guru's...

    hi St-Drome,
    Try to create your own document.
    textfield.setDocument(new MyDocument());
    class MyDocument extends PlainDocument {
    public MyDocument() {}
    public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException {
    if (!str.equals("a")) {
    super.insertString(offs, str, a);
    else {
    return;
    Alex

  • JTextPane Text Coloring

    I'm attempting to make a text editor - a programmer's tool - that colors certain keywords as they are typed in. I'm using a JTextPane and a DocumentListener to wait for keypresses that modify the document text. When each letter is typed, the listener expands the offset and the length to include the entire word. This works, I've checked. If I type hello the program recognizes it as a word. If I press the spacebar and then type test the program recognizes test as a separate word, the current one.
    However, when I try to removeString from the document, or try to insertString with a MutableAttributeSet that is not the LogicalStyle of the document, it gives me this error:
    Exception occurred during event dispatching:
    java.lang.IllegalStateException: Attempt to mutate in notification
            at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1090)
            at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:511)
            at Language.Editor.ColorCommand.insertUpdate(ColorCommand.java:63)
            at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:180)
            at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:542)
            at javax.swing.JTextPane.replaceSelection(JTextPane.java:159)
            at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:801)
            at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1384)
            at javax.swing.JComponent.processKeyBinding(JComponent.java:2078)
            at javax.swing.JComponent.processKeyBindings(JComponent.java:2104)
            at javax.swing.JComponent.processKeyEvent(JComponent.java:2050)
            at javax.swing.JEditorPane.processKeyEvent(JEditorPane.java:1159)
            at javax.swing.text.JTextComponent.replaceInputMethodText(JTextComponent.java:2793)
            at javax.swing.text.JTextComponent.processInputMethodEvent(JTextComponent.java:2654)
            at java.awt.Component.processEvent(Component.java:3558)
            at java.awt.Container.processEvent(Container.java:1164)
            at java.awt.Component.dispatchEventImpl(Component.java:2593)
            at java.awt.Container.dispatchEventImpl(Container.java:1213)
            at java.awt.Component.dispatchEvent(Component.java:2497)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)Anyone have any idea how I can fix this?

    I solved this at the character level rather than the word level but the principle will still apply. It looks like you went down the same road I did originally.
    What you really need to do is extend DefaultStyledDocument and override the insertString() method. I used something like:
    import java.awt.Color;
    import javax.swing.text.*;
    public class MyDoc extends DefaultStyledDocument {
      static MutableAttributeSet charA, charB, defaultAttr;
      public MyDoc() {
        charA = new SimpleAttributeSet();
        StyleConstants.setForeground(charA, Color.red);
        charB = new SimpleAttributeSet();
        StyleConstants.setForeground(charG, Color.blue);
        defaultAttr = new SimpleAttributeSet();
        StyleConstants.setForeground(charN, Color.black);
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (str == null) return;
        char[] c = str.toCharArray();
        for(int i = 0; i < c.length; i++) {
          try {
            if (c == 'A' || c == 'a') {
              super.insertString(offs+i, String.valueOf(c), charA);
    } else if (c == 'B' || c == 'b') {
    super.insertString(offs+i, String.valueOf(c[i]), charB);
    } else {
    super.insertString(offs+i, String.valueOf(c[i]), defaultAttr);
    } catch (BadLocationException ble) {
    throw ble;
    Then used the following to attach MyDoc to a text pane:
    DefaultStyledDocument doc = new MyDoc();
    JTextPane jtp = new JTextPane(doc);Now when I use jtp all a and b characters are coloured, and all other characters are a black.
    So for your problem I would suspect you need to create a MutableAttributeSet for each word you wish to highlight. Overide insertString() split/tokenize the str argument. Finally send the tokens with the correct MutableAttributeSet to the insertString() method of the super class.
    If you want the text to auto highlight as people are typing then it should simply be a case of identifying the next word boundry, remove the text between the previous and this word boundry, test the word and insert it back using the correct MutableAttributeSet.
    Hope this helps

  • Line wrap.

    Hey guys, i am trying to learn how to do word wrap on Jtextareas....i found this code by surfing this site, i implemented it into my code but the line wrap had no effect.
    I think i have to set a value somewhere to say after 200chars do a line wrap and go to next line. But i cant find how to do this anywhere.
    Will anyone please tell me how to set how many chars can be on each line?
    (sorry if this question isnt specific enough, but i am stuck for aboout 2 hours on this problem)
    JTextArea textArea = new JTextArea(
        "This is an editable JTextArea " +
        "that has been initialized with the setText method. "
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    Hi guys still trying to figure out that new line thingy...I am getting close, but i have an error that i cant solve, can any see what is wrong, i have pasted the error at the end..
    here is my code:
    JTextArea resourceDescField = new JTextArea();
         JScrollPane resourceDescFieldScrollPane = new JScrollPane(resourceDescField);
    resourceDescField.getDocument().addDocumentListener(new MyDocumentListener());
            resourceDescField.getDocument().putProperty("name", "Text Area");
    class MyDocumentListener implements DocumentListener
              String newline = "\n";
              public void insertUpdate(DocumentEvent e)
                  updateLog(e, "inserted into");
              public void removeUpdate(DocumentEvent e)
                  updateLog(e, "removed from");
              public void changedUpdate(DocumentEvent e)
              public void updateLog(DocumentEvent e, String action)
                  Document doc = (Document)e.getDocument();
                  int changeLength = e.getLength();             
                   if(changeLength > 150);
                   resourceDescField.append(resourceDescField.getText()+newline);
         }here is my error:
    Exception occurred during event dispatching:
    java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.JTextArea.append(Unknown Source)
    at UpdateResource$MyDocumentListener.updateLog(UpdateResource.java:191)
    at UpdateResource$MyDocumentListener.insertUpdate(UpdateResource.java:17
    6)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source)
    at javax.swing.text.AbstractDocument.insertString(Unknown Source)
    at javax.swing.text.JTextComponent.replaceSelection(Unknown Source)
    at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerform
    ed(Unknown Source)

  • KeyReleased Event

    Hi everybody,
    i have a JTable and what I want to is that when the user type something in the TextField the table will show the names of the company that start with the letter that the user typed. But the problem is that each time the user type the event executes 2 times, this is the code:
    private void txt_searchCompanyKeyReleased(java.awt.event.KeyEvent evt) {
    TableModel model = jt_Company.getModel();
    ArrayList<String[]> dataArray = new ArrayList<String[]>();
    String[] data = new String[ jt_Company.getRowCount() ];
    String s = txt_searchCompany.getText();
    System.out.println("Cantidad de filas: " + jt_Company.getRowCount()+ "\nCantidad de col: " + jt_Company.getColumnCount());
    for(int i = 0; i < jt_Company.getRowCount(); i++)
       for(int j = 0; j < model.getColumnCount(); j++)
           if(model.getValueAt(i, 1).toString().startsWith(s) == true)
             data = model.getValueAt(i, j).toString();
             dataArray.add(data);
              System.out.println(" " + data[0] + "Tamano de ArrayList: " + data.  length);
    jt_Company.setModel(new Business.CompanyTable(dataArray));
    }//End of the methodthe method compares very well the string and the name of the companies in each row, but as mention before the method does it 2 times that means that the string array will the double of rows.
    How can I do to make the event execute only one time
    Thanks a lot.......

    Hi camickr, i tried what you said and It works well, but now i am traying to do another thing.
    Look, i want that the textfield remove the last character when the user type one of this character: ( ' / * % ? = > < etc...)and this is the code:
    class MyDocumentListener implements DocumentListener {
        /** Creates a new instance of MyDocumentListener */
        public MyDocumentListener() {
        public void insertUpdate(DocumentEvent e) {
          updateLog(e);
        public void removeUpdate(DocumentEvent e) {
          updateLog(e);
        public void changedUpdate(DocumentEvent e) {
        //Plain text components don't fire these events.
        public void updateLog(DocumentEvent e) {
           int i = e.getDocument().getLength();
           String name = " ";
           try{
                name = e.getDocument().getText(i-1, 1);
                if(restriction.restrictionSearchBy(name) == true)
                   JOptionPane.showMessageDialog(null, "Hola" + name);
                   txt_searchCompany.getDocument().remove(i-1, 1);
                   e.getDocument().remove(i-1, 1);// I tried this and did not work also
                else{
           catch(javax.swing.text.BadLocationException b){}
    }but i got this exception when i run it:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1343)
    at javax.swing.text.AbstractDocument.remove(AbstractDocument.java:569)
    at Client.MDIFrame$MyDocumentListener.updateLog(MDIFrame.java:867)
    at Client.MDIFrame$MyDocumentListener.insertUpdate(MDIFrame.java:847)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:184)
    at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:754)
    at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:711)
    at javax.swing.text.PlainDocument.insertString(PlainDocument.java:114)
    at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:673)
    at javax.swing.text.JTextComponent.replaceSelection(JTextComponent.java:1099)
    at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:839)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1571)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2763)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2798)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2726)
    at java.awt.Component.processEvent(Component.java:5265)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1810)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:672)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:920)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:798)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:636)
    at java.awt.Component.dispatchEventImpl(Component.java:3841)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Window.dispatchEventImpl(Window.java:1774)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    what can i do the remove it.
    Thanks a lot....

  • How to insertString in document listener

    I always got java.lang.IllegalStateException: Attempt to mutate in notification.
    I do not want to extend defaultstyleddocument. is there any solution for it.
    thanks a lot.

    Hello,
    what do you want to achieve ? Offer some source-code.
    If you want your special behaviour for your document override its insertString method. For example if you want a maximum length try this:public void insertString(int offs, String str, AttributeSet a)
                        throws BadLocationException
         int length = getLength();
         if ((length += str.length()) > maxChar)
              //don't insert if current chars > max chars
              return;
         super.insertString(offs, str, a);
    }regards,
    Tim

  • Desperate help need with Document Listener

    I'm working on a very cool freeware Java text editor, that is working beautifully, except for the code used to change the color of reserved words, etc, on the fly...
    At the moment, I use a documentlistener. When text is inserted, I need to color some of that text automatically. However, when I try to call setCharacterAttributes in DefaultStyledDocument, it causes a runtime exception, Illegal State Exception (Attempt to mutate in notification)>
    I understand how this exception is caused, but how do I get around it?

    Thanks for the replies. They were very helpful, and I have now managed to sort the problem, although in a different way that involves using the key listening class you can add to containers...
    The java editor is called j-Scribe, and is a text editor dedicated to java. I've designed it to be more user friendly than other text editors, with a useful interface. The code dispplay is all highlighted, and clicking on a brace collapses that section of code, to make larger classes easier to work through... There are also some nifty filemanagement windows, including a history pane similar to IE6, and one click access to all open files, and one click access to all of their save and close functions... There are wizards to automate creation of certain elements of code, and eventually a number of intelligent features will be added. The program makes extensive use of xml to store all of the information generated by the program.
    I'm working on the alpha version right now, for release in about two weeks. The beta will be out three - four weeks after that, and the release should be late September / early October time...
    If you're interested, e-mail me and I'll add you to the list for the alpha and beta test releases...
    [email protected]

  • Urgent Tricky problem... I challenge you all....

    I'm working on a very cool freeware Java text editor, that is working beautifully, except for the code used to change the color of reserved words, etc, on the fly...
    At the moment, I use a documentlistener. When text is inserted, I need to color some of that text automatically. However, when I try to call setCharacterAttributes in DefaultStyledDocument, it causes a runtime exception, Illegal State Exception (Attempt to mutate in notification)>
    I understand how this exception is caused, but how do I get around it?

    Hi,
    You'll need to modify the color after your DocumentListener event handling is finished.
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        //setCharacterAttributes ...
    });Then the change is done when the document is no longer locked.
    Hope this helps,
    Kurt.

  • MVC problem - infinite loop?

    I'm going to use a horribly oversimplified example to make my point here, because if I were to describe the actual code I'm looking at, it would take the better part of the afternoon and I'd probably bore you all to tears in the process. So, for the sake of argument, let's assume the following model object:
    public class MyModelObject
      private int a;
      private int b;
      private int c;
      public void setA(int newA)
        a = newA;
        b = newA + SOME_CONSTANT;
        c = newA + SOME_OTHER_CONSTANT;
      public void setB(int newB)
        this.setA(SOME_CONSTANT-newB);
      public void setC(int newC)
        this.setA(SOME_OTHER_CONSTANT-newC);
      public int getA()
        return a;
      public int getB()
        return b;
      public int getC()
        return c;
    }So what we see from this is that the setter for one class property actually changes the value of all three class properties (whether this is good design or not is questionable, but keep in mind this is a horribly simplified example for discussion purposes). The point is that the rules regarding the internal state of MyModelObject are governed entirely within that class - the controller and view don't know about these rules (again, questionable design, but bear with me here).
    Now let's imagine we have a view class that displays a MyModelObject instance and allows the user to change the value of a, b, or c. We also have a controller class that observes the view and responds to changes. When the user modifies the value of, let's say b, the controller will respond to that change by calling the setB() method in MyModelObject. Problem is, now the model and the view are out of synch... someone has to tell the view that the other two class properties have also been modified as a result of calling setB() - whose responsibility is this? Should the model inform the view that something has changed so that the view can redisplay it, or should the view observe the model and automatically redisplay whenever the model is modified?
    More importantly - let's say the controller is observing the view for changes, and the view is observing the model for changes... how do you avoid an infinite loop? For example, the user changes the value of b in the view, which causes the internal state of MyModelObject to be modified, which causes a change in the view, which causes a change in the model, and so on and so forth.
    A twist on the above problem is that it is illegal in some Swing components (JTextPane, for instance) to modify the view while a change notification is in progress... so something like this would throw an IllegalStateException:
    //somewhere in the controller
    public void insertUpdate(DocumentEvent docEvent)
      //update the model
      myModelObject.handleChange(docEvent);
      //now redisplay since the model has changed:
      myTextPane.display(myModelObject);
      // IllegalStateException is raised - Attempt to mutate in notification
    }This fails because you can't change the state of the view component in the event handler for a view change event. How do you get around this using proper MVC architecture? Or am I completely out to lunch here?

    The view shouldn't send events to the controller unless they make sense... For example, it shouldn't fire a change event when the user types in a new value. But only if the user presses enter, or the view loses focus (if this gesture is taken as equivalent).
    So when the change of the view comes from the side-effects of a setter of some property, it should fire no event (so that it will not loop). So it sounds no big problem (if such a distinction of events is easy - it should).

  • Illegal state exception in Document Listener

    Hi folks,
    Iam getting the IllegalStateException when iam trying to update the document in the Document Listener.
    spec says iam not supposed to mutate the document in the document Listener.
    My requirement is that: when user types any java key word in JTextPane..I need to change it's color. I tried this in DocumentListener and CaretListener. But Iam getting following Exception:
    Exception occurred during event dispatching:
    java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:971)
    is there any alternative way to do this?
    thanks in advance!!
    -TSR

    Take the code that you are using to update the document and submit it to Swing to run later, like this:
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // your code goes here

  • DOcumentEvent question (ERROR)

    ok heres my code
    class PaneDocumentListener implements DocumentListener
    public void insertUpdate(DocumentEvent e)
         PaneDocumentListener(e);
    public void removeUpdate(DocumentEvent e)
         PaneDocumentListener(e);
    public void changedUpdate(DocumentEvent e)
         PaneDocumentListener(e);
    public void PaneDocumentListener(DocumentEvent e)
         Document doc=(Document)e.getDocument();
         Label.setText(JTP.getText());
         try
         JTP.setText(JTP.getText().replace("public","cool"));
         catch(Exception errorr)
         System.out.println(errorr);
    }JTP is a textpane
    im trying to change the word "public" in the textpaen with the word "cool"
    using a document listner.but i got an errorr
    java.lang.IllegalStateException:Attempt to mutate in notification
    can any1 help me??
    or i shoouldnt use this method??
    thanks
    thanks

    i tried this
    doesnt work
              public void PaneDocumentListener(DocumentEvent e)
                   Runnable run-new Runnable()
                        public void run()
                        Document doc=(Document)e.getDocument();
                        Label.setText(JTP.getText());
                             try
                             JTP.setText(JTP.getText().replace("public","cool"));
                             catch(Exception errorr)
                             System.out.println(errorr);
                   SwingUtilities.invokeLater(run);
              }

Maybe you are looking for

  • Adobe Reader And SharePoint Workflow: How To?

    Hi all, We are using SharePoint 2010 as our collaboration portal. Our Marketing department wants to use feedback workflows on PDF documents. The PDF documents can be commented and all reviewers should be able to do that in turn or parallel. We can st

  • [SOLVED] Pacman and ABS sync give different results

    I have been having a few issues with the NZ mirror, however they have been sorted. I have -Syy'ed a couple of times and get back: :: Starting full system upgrade... local database is up to date Which I know isn't the case as I visited the mirror via

  • Kernel Panic Safari Webprocess

    Hello, It happened this afternoon, my macbook pro mi 12, 13 inch, crashed twice times. I was on Safari on Tumblr normally. My display is normal, an LG, and is connected by VGA adaptor from Apple. Here is the kernel report, can you please find out my

  • Totals in Query

    Hi Everybody, Question: Is it possible to have total of a specific column when I create a query? In my example I created a query for all the costs related to a project (tables OPOR and POR1). I have the column of the price of every lineitem (Price fr

  • B85M-G43 Integrated Graphics memory

    I am using an i5-4570 processor which has the integrated HD4600 graphics capability. Do I need to worry about the BIOS setting for "Integrated Graphics Share Memory"? It offers 32M, 64M, 128M and 256M. But the 4600 can share well over 1GB of memory.