1

I have this code, that "disables" user input on a JTextField after n characters are inserted:

JTextField tf = new JTextField();
tf.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        if (((JTextField) e.getSource()).getText().length() > n) {
            e.consume();
        }
    }
});

It works, but i was wondering if there is an alternative, because i tried it on an old slow computer and when i type something in the textfield the letter is added, then it disappear... I would like to avoid using e.consume() after user input and directly prevent insertion instead.

Is it possible?

EDIT

I forgot to mention that i used JTextField only for this example, but i would like this code to work with generic text input components like JTextPane, JTextArea, etc

mKorbel
  • 109,525
  • 20
  • 134
  • 319
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • this might help: http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield – Cristina_eGold May 21 '13 at 13:50
  • It seems like documentFilter is the way to go for all these cases. JTextPane supports documents, and as for JTextArea: http://www.linuxquestions.org/questions/programming-9/java-jtextarea-limiting-amount-of-characters-entered-155469/#post805335 – Menelaos May 21 '13 at 14:06
  • Anything that implements the `JTextComponent` interface has a document. If the specific document supports the setDocumentFilter (e.g. as in `AbstractDocument`) you can use the this method . http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html . – Menelaos May 21 '13 at 14:11

1 Answers1

3

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(); }
Menelaos
  • 23,508
  • 18
  • 90
  • 155