Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with DocumentListener

Tags:

java

swing

I have a JTextField that I want to be limited to fifteen characters. The problem is that when I type over 15 characters, it errors. How can i fix this? Do I have to use some other object?

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

 final int maxNicknameLength = 15;
 final JTextField nickname = new JTextField(1); //Max length: 15
 DocumentListener docListen = new DocumentListener() {
      public void changedUpdate(DocumentEvent e) {
           lengthCheck(e, nickname, maxNicknameLength);
      }

      public void insertUpdate(DocumentEvent e) {
           lengthCheck(e, nickname, maxNicknameLength);
      }

      public void removeUpdate(DocumentEvent e) {
           lengthCheck(e, nickname, maxNicknameLength);
      }
      public void lengthCheck (DocumentEvent e, JTextField txt, int max) {
           if (txt.getText().length() > max)
                txt.setText(txt.getText().substring(0, max));
      }    
 };
 nickname.getDocument().addDocumentListener(docListen);
like image 416
Jack Avatar asked Nov 18 '25 14:11

Jack


2 Answers

Use a DocumentFilter, not a DocumentListener. By the time the listener fires the Document has already been updated. A filter will prevent the document from being updated.

See: Implementing a Document Filter for a working example that does what your want.

like image 135
camickr Avatar answered Nov 20 '25 04:11

camickr


Try this:

public void lengthCheck(final DocumentEvent e, final JTextField txt, 
        final int max) {
    if (txt.getText().length() > max) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                txt.setText(txt.getText().substring(0, max));
            }
        });
    }
}
like image 34
hoipolloi Avatar answered Nov 20 '25 04:11

hoipolloi