在Swing GUI中显示字符数 [英] show character count in swing gui
问题描述
我有一个名为taMessage
的JTextArea
,它显示一条消息字符串.用户可以在运行时编辑此字符串.
我有一个JLabel lblLength
来显示字符数.我正在使用lblLength.setText(taMessage.getText().length()+"/ 160");
来显示字符数.
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.
我应该为taMessage使用哪个事件侦听器,以便当我在文本区域中继续键入文本时,lblLength会继续更新自身?
What event listener should I use for taMessage so that as I keep typing text in my text area, lblLength keeps on updating itself?
类似于在way2sms或160by2这样的站点中看到的东西,它显示了剩余的字符数.
Something like we see in sites like way2sms or 160by2, where it shows the number of characters left.
推荐答案
A DocumentListener 可能是最好的选择.您甚至不需要创建新的类,只需内联定义它即可.
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");
}
});
这篇关于在Swing GUI中显示字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!