Pages

Thursday, May 17, 2012

Vaadin - TextField componet, value change listener

Working with TextField component in Vaadin framework web environment, is much like, working with components in swing/awt applications. Here, we also have events and listeners.
For example, changing a value in a TextField componet, can be captured right after the field, loses focus.



Just have the following class and add to your Vaadin web application:

public class MyApplication extends Application {
    //global components
    TextField tfInput;
    Window mainWindow;
   
    //main method - init()
    @Override
    public void init() {
    mainWindow = new Window("MyApplication");
        tfInput = new TextField("Enter your Name: ");
        tfInput.setValue("empty");
       
        //handling the change of the texfield value property:
        tfInput.addListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(ValueChangeEvent event) {
                // Assuming that the value type is a String
                String value = (String) tfInput.getValue();               
                Window.Notification notif = new Window.Notification("Be warned "+value+"!",
                        "<br/>This message warning, after a field value change, stays centered, till you do sthg!",
                        Window.Notification.TYPE_WARNING_MESSAGE);
                notif.setPosition(Window.Notification.POSITION_CENTERED);
                mainWindow.showNotification(notif);
            }           
        });       
        // Fire value changes immediately when the field loses focus
        tfInput.setImmediate(true);       
               
    mainWindow.addComponent(tfInput);
    setMainWindow(mainWindow);
    }
}

The same thing you can achieve by binding the TextField component to an ObejectProperty value. The change of this ObjectProperty value, is immediately reflected anywhere.

public class MyApplication extends Application {
    Double trouble = 42.0;
    final ObjectProperty<Double> property = new ObjectProperty<Double>(trouble);
      
    @Override
    public void init() {
    Window mainWindow = new Window("MyApplication");
        TextField tf = new TextField("The Answer",property);
        tf.setImmediate(true);
       
        Label feedback = new Label(property);
        feedback.setCaption("The Value");
       
        Panel pnl = new Panel();
        pnl.addComponent(tf);
        pnl.addComponent(feedback);
       
    mainWindow.addComponent(pnl);
    setMainWindow(mainWindow);
    }
}

Just try it and test, this code on: http://lehelsipos.appspot.com/

2 comments: