Roughian Examples Site Map - Examples - Tutorials

ChangeListener


Version 1.0 onwards

Lets You Run Code When Text Changes



Sources



Notes


As a general trend, onChange indicates a change in the text of a user-supplied text box. However, this event can and is defined by the widgets supplying it.

The event is NOT fired if the user types a character (which is a tad confusing since the text has actually changed), it fires when, say, a TextBox loses focus and the text is different to the text that was in the box when the widget was given focus.


Code

If you are new to listeners, then this isn't the simplest of examples, I'd have a look at the Button example under GWT Widgets for that


static int LOG_RECORDS = 500;
static int LOG_DISPLAY = 10;

class Demo extends Composite implements ChangeListener, FocusListener
{
    TextBox textbox = new TextBox();
    ListBox listbox = new ListBox();

    String oldText = "";
    public Demo()
    {
        VerticalPanel widget = new VerticalPanel();
        Label label;

        initWidget(widget);
        widget.addStyleName("demo-panel");

        label = new Label("Enter Text and then hit the Tab Key:");
        widget.add(label);
        widget.add(textbox);
        widget.setCellWidth(textbox, "100%");
        textbox.setWidth("100%");

        label = new Label("Log:");
        widget.add(label);

        widget.add(listbox);
        widget.setCellWidth(listbox, "100%");
        listbox.setWidth("100%");
        listbox.setVisibleItemCount(LOG_DISPLAY);
        listbox.setStyleName("demo-ChangeListener-listbox");

        textbox.addChangeListener(this);
        textbox.addFocusListener(this);

        new Timer()
        {
            public void run()
            {
                textbox.setFocus(true);
            }
        }.schedule(1);
    }
    public void onChange(Widget sender)
    {
        log("onChange() event was fired");
    }
    public void onFocus(Widget sender)
    {
        log("Got Focus");
    }
    public void onLostFocus(Widget sender)
    {
        log("Lost Focus");
    }
    void log(String text)
    {
        listbox.insertItem(text, 0);
        while (listbox.getItemCount() > LOG_RECORDS)
            listbox.removeItem(LOG_RECORDS);
    }
}