Question

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

Was it helpful?

Solution

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(); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top