You can use the DocumentSizeFilter
class
Which is made for this specific use: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/DocumentSizeFilter.java
Tutorial on how to do this within Implementing a Document Filter Section:
Quoting from there:
To limit the characters allowed in the document, DocumentSizeFilter overrides the DocumentFilter class's insertString method, which is called each time that text is inserted into the document. It also overrides the replace method, which is most likely to be called when the user pastes in new text. In general, text insertion can result when the user types or pastes in new text, or when the setText method is called. Here is the DocumentSizeFilter class's implementation of the insertString method:
public void insertString(FilterBypass fb, int offs,
String str, AttributeSet a)
throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
super.insertString(fb, offs, str, a);
else
Toolkit.getDefaultToolkit().beep(); }