简体   繁体   中英

show character count in swing gui

I have a JTextArea called taMessage which displays a message string. This string can be edited by the user at run time.
I have a JLabel lblLength to show the number of characters. I am using lblLength.setText(taMessage.getText().length()+"/ 160"); to display the character count.

What event listener should I use for taMessage so that as I keep typing text in my text area, lblLength keeps on updating itself?

Something like we see in sites like way2sms or 160by2, where it shows the number of characters left.

Swing text fields and text areas are backed by a class called Document that can have a Document Listener attached to it.

The official docs have a decent tutorial on Document Listeners .

You would want to attach the document listener, and since you're interested in character counts then you'd simply want to use the same code you used above to initialize the label in all three of the Document Listener's callback methods.

In an MVC like way you can listen to the document's change.

JTextArea ta = ...;
JLabel lblLength = ...;
Document taDoc = ta.getDocument();
taDoc.addDocumentListener(new CharacterCounterDocumentListener(lblLength))


public class CharacterCounterDocumentListener implements DocumentListener {

     private JLabel counterLabel;        

     public CharacterCounterDocumentListener(JLabel counterLabel){
         this.counterLabel = counterLabel;
     }

     public void changedUpdate(DocumentEvent e) {
        Document d = e.getDocument();
        int length = d.getLength();
        counterLabel.setText(Integer.toString(length));
     }
     public void insertUpdate(DocumentEvent e)  {
     }
     public void removeUpdate(DocumentEvent e) {
     }
}

A DocumentListener is probably your best bet. You don't even need to create a new class, you can just define it inline.

// Listen for changes in the text
taMessage.getDocument().addDocumentListener(new DocumentListener() {
    public void changedUpdate(DocumentEvent e) {
        update();
    }

    public void removeUpdate(DocumentEvent e) {
        update();
    }

    public void insertUpdate(DocumentEvent e) {
        update();
    }

    public void update() {
        lblLength.setText(taMessage.getText().length()+"/ 160");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM