GWT TextArea Listener

I am trying to use gwt to create a text field and a counter below it with a character length, but it does not take into account the inverse space and with 1 character has a length of 0. Here is my code. What could be the problem?

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); } 
+4
source share
3 answers

Perhaps you want to track the KeyUp event:

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

I think this code should work

 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()); } }); } 

}

+3
source

It looks like you are counting the characters before completing the keystroke. Perhaps if you try KeyUpHandler instead, then the text area will include the newly added character.

+1
source

Source: https://habr.com/ru/post/1332352/


All Articles