Error with DocumentListener

I have a JTextField that I want to limit to fifteen characters. The problem is that when I print more than 15 characters, these are errors. How can i fix this? Should I use any other object?

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);
+2
source share
3 answers

Use a DocumentFilter, not a DocumentListener. By the time the listener is listening, the document has already been updated. The filter will prevent the document from updating.

See: Implementing a document filter for a working example that does what you want.

+8
source

:

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));
            }
        });
    }
}
+3

Java tutorial:

, . . , , , . .

Document , , lengthCheck. setText JTextField Document, .

+1

Source: https://habr.com/ru/post/1541887/


All Articles