简体   繁体   English

在Swing GUI中显示字符数

[英]show character count in swing gui

I have a JTextArea called taMessage which displays a message string. 我有一个名为taMessageJTextArea ,它显示消息字符串。 This string can be edited by the user at run time. 用户可以在运行时编辑此字符串。
I have a JLabel lblLength to show the number of characters. 我有一个JLabel lblLength来显示字符数。 I am using lblLength.setText(taMessage.getText().length()+"/ 160"); 我正在使用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? 我应该为taMessage使用哪个事件侦听器,以便在我在文本区域中键入文本时,lblLength能够不断更新自身?

Something like we see in sites like way2sms or 160by2, where it shows the number of characters left. 就像我们在way2sms或160by2这样的站点中看到的那样,它显示了剩余的字符数。

Swing text fields and text areas are backed by a class called Document that can have a Document Listener attached to it. Swing文本字段和文本区域由名为Document的类支持,该类可以附加有Document Listener。

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. 以类似于MVC的方式,您可以收听文档的更改。

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. DocumentListener可能是您最好的选择。 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");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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