Vaadin Web应用开发教程(10):UI组件-TextField

jerry VaadinWeb 2015年11月25日 收藏

TextField文本框,可以接受用户输入文字。它实现Field接口,支持数据绑定。基本用法:

  1. // Create a text field
  2. TextField tf = new TextField("A Field");
  3. // Put some initial content in it
  4. tf.setValue("Stuff in the field");
  5.  

显示如下:

支持Field接口的UI组件,可以通过Property.ValueChangeListener 来监视Value的变化。可以通过方法getValue()来取代TextField的当前值。参考下面代码片段:

  1. // Handle changes in the value
  2. tf.addListener(new Property.ValueChangeListener() {
  3. public void valueChange(ValueChangeEvent event) {
  4. // Assuming that the value type is a String
  5. String value = (String) tf.getValue();
  6.  
  7. // Do something with the value
  8. getWindow().showNotification("Value is:", value);
  9. }
  10. });
  11.  
  12. // Fire value changes immediately when the field loses focus
  13. tf.setImmediate(true);

TextField由AbstractTextField派生而来,因此继承了AbstractTextField的大部分API。下图为AbstractTextField的类关系图:

 数据绑定

实现Field接口的UI组件支持数据绑定,TextField可以绑定到支持和 String 互换的数据类型。比如下面代码将TextField 绑定到一个Double数据变量。

  1. // Have an initial data model. As Double is unmodificable and
  2. // doesn't support assignment from String, the object is
  3. // reconstructed in the wrapper when the value is changed.
  4. Double trouble = 42.0;
  5.  
  6. // Wrap it in a property data source
  7. final ObjectProperty<Double> property =
  8. new ObjectProperty<Double>(trouble);
  9.  
  10. // Create a text field bound to it
  11. TextField tf = new TextField("The Answer", property);
  12. tf.setImmediate(true);
  13.  
  14. // Show that the value is really written back to the
  15. // data source when edited by user.
  16. Label feedback = new Label(property);
  17. feedback.setCaption("The Value");
  18.  

字符串长度

可以通过setMaxLenght() 指定文本框可以输入的字符串长度。为安全起见,TextField 的值传到服务器端时会截去超过最大长都的部分。

处理Null 值

TextField 可以绑定到某些支持Null值的数据源,如数据库的某个字段。此时,你可能想以某种特殊方式表示Null值,可以通过setNullRepresentation() 设置但当数据源为Null时显示内容。 setNullSettingAllowed 可以控制是否允许用客输入null 值,当setNullSettingAllowed 为假时,输入的Null 代表字符串null,而非Null值。

比如:

  1. // Create a text field without setting its value
  2. TextField tf = new TextField("Field Energy (J)");
  3. tf.setNullRepresentation("-- null-point energy --");
  4.  
  5. // The null value is actually the default
  6. tf.setValue(null);
  7.  
  8. // Allow user to input the null value by
  9. // its representation
  10. tf.setNullSettingAllowed(true);
  11.  
  12. // Feedback to see the value
  13. Label value = new Label(tf);
  14. value.setCaption("Current Value:");

结果如下:

Text 文本变化事件
除了通用的Property.ValueChangeListener 之外,TextField可以使用TextChangeListner 来监视Text内容的变化。immediate 模式实际上并非是立即触发Text内容变化事件,而是发生在TextField失去Focus后。
TextField 文本变化事件触发的时机有三种模式:TextChangeEventMode.LAZY (默认模式),TextChangeEventMode.TIMEOUT TextChangeEventMode.EAGER
TextChangeEventMode.EAGER 表示每次按键都会触发事件,而TextChangeEventMode.TIMEOUT  表示每隔指定时间段时触发事件,而TextChangeEventMode.LAZY 则表示在输入暂停的某个时刻触发事件。
对于Web应用来说,使用默认模式可以适用大部分情况。