Search code examples
javamultithreadingswingjtextfieldtwitter4j

Update method in JFrame


I'm creating a Twitter client in Java with Twitter4j. My intention is to make a count that tells you how many characters are remaining for your tweet. It would start with 140 and with every character I wrote it would be updated. I have been thinking a bit and it would be something like this:

int count = 140;
count = count - textField.getText().length();
chCount.setText(Integer.toString(count));

The problem is that I don't know how to update run that code constantly. I have tried with the update() method but it isn't being called

Thanks in advance


Solution

  • Attach a document listener to the document of the text field, and call your counter method from that.

    textField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        void changedUpdate(DocumentEvent e) {}
        @Override
        void insertUpdate(DocumentEvent e) {
            // Your counter method
            updateCount();
        }
        @Override
        void removeUpdate(DocumentEvent e) {
            updateCount();
        }
    });