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);
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.
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));
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With