Java JTextField text length not updating after deleting characters
<p>I am trying to create a JTextField with a key listener that will enable a button only when the length of the text is exactly 4.</p>

<p>It's working but if length of 4 is reached, and I delete a character (using backspace or delete buttons) the text length isn't updated and keeps being 4, until I remove another character, but that will make it actually 2 characters.</p>

<p>Can you help me with the code to make it update the length? Thanks in advance.</p>

<p>I already tried these <strong>without success</strong>:</p>

<pre><code>Document doc = field.getDocument();
if (doc.getLength() &gt; 0) {
    try {
        doc.remove(field.getCaretPosition(), 1);
    } catch (BadLocationException e1) {
    }
}
</code></pre>

<p>and</p>

<pre><code>field.setText(field.getText().substring(0, field.getText().length()));
</code></pre>