GWT: input textArea with character counter implementation


Below is the implementation for above picture. This is a method that creates custom text area that accepts 140 input characters only. As user types in characters the counter decrements/increments accordingly, when number of characters exceeds 140, the number color turns red as shown above.

private void buildTextMessageRow(final Object msg, VerticalPanel container)
    {
safeTextArea.setText("");
safeTextArea.addStyleName("myTextBoxStyle");
safeTextArea.setWidth("400px");

Row title = new Row(noWrapLabel("Enter your text message: (maximum 140 charachters)"), null);
container.add(title);

HorizontalPanel remainCharsPanel = new HorizontalPanel();
remainCharsPanel.add(new HTML("You have "));
final Label remainingCharsLabel = new Label("140");
remainCharsPanel.add(remainingCharsLabel);
remainCharsPanel.add(new HTML(" characters left."));
container.add(new Row(null, safeTextArea));
container.add(new Row(null, remainCharsPanel));

safeTextArea.addKeyPressHandler(new KeyPressHandler()
{
    public void onKeyPress(KeyPressEvent event)
    {
onTextAreaContentChanged(remainingCharsLabel);
    }

});
safeTextArea.addFocusHandler(new FocusHandler()
{
    public void onFocus(FocusEvent event)
    {
onTextAreaContentChanged(remainingCharsLabel);
    }
});
//onFocusLost previously
safeTextArea.addBlurHandler(new BlurHandler()
{

    public void onBlur(BlurEvent event)
    {
onTextAreaContentChanged(remainingCharsLabel);
    }
});
    }


    private void onTextAreaContentChanged(final Label remainingCharsLabel)
    {
int counter = new Integer(safeTextArea.getText().length()).intValue();

int charsRemaining = 140 - counter;
remainingCharsLabel.setText("" + charsRemaining);
if (charsRemaining >= 0)
{
    remainingCharsLabel.setStyleName("my_form_under_140_chars");
} else
    remainingCharsLabel.setStyleName("my_form_over_140_chars");
    }




As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles