GWT TextArea监听器

时间:2010-12-16 14:13:34

标签: java gwt

我尝试使用gwt创建一个textarea和一个带有字符长度的计数器,但它不计算退格,并且1个字符的长度为0.这是我的代码。可能是什么问题?

public class Test implements EntryPoint {

 TextArea textArea;
 Label  counter;

 public void onModuleLoad() {
  textArea = new TextArea();
  counter = new Label("Number of characters: 0");
  textArea.addKeyPressHandler(new KeyPressHandler() {
        public void onKeyPress(KeyPressEvent event) {
       counter.setText("Number of characters: " + textArea.getText().length());
   }
  });
  RootPanel.get("myContent").add(textArea);
  RootPanel.get("myContent").add(counter);
}

3 个答案:

答案 0 :(得分:4)

也许您想要跟踪 KeyUp 事件:

textArea.addKeyUpHandler(new KeyUpHandler() {
    public void onKeyUp(KeyUpEvent event) {
        counter.setText("Number of characters: " + textArea.getText().length());
    }
});

答案 1 :(得分:3)

我认为检查此代码应该有效

public class TextAreaEx implements EntryPoint {
 final TextArea textArea = new TextArea();
 final Label counter = new Label("Number of characters: 0");

public void onModuleLoad() {
    RootPanel.get().add(textArea);
    RootPanel.get().add(counter);
    addlistener();
}

private void addlistener() {
       textArea.addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent keyUpEvent) {
              counter.setText(" Number of characters:"+textArea.getText().length());
            }
        });
        textArea.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent changeEvent) {
                counter.setText(" Number of characters:"+textArea.getText().length());
            }
        });
  }

}

答案 2 :(得分:1)

听起来你在按键事件完成之前计算字符数。也许如果您尝试使用KeyUpHandler,则文本区域将包含新添加的字符。