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

来源:互联网 发布:体积最小的单片机 编辑:程序博客网 时间:2024/04/30 13:03

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

// Create a text fieldTextField tf = new TextField("A Field");// Put some initial content in ittf.setValue("Stuff in the field");


显示如下:


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

// Handle changes in the valuetf.addListener(new Property.ValueChangeListener() {    public void valueChange(ValueChangeEvent event) {        // Assuming that the value type is a String        String value = (String) tf.getValue();        // Do something with the value        getWindow().showNotification("Value is:", value);    }});// Fire value changes immediately when the field loses focustf.setImmediate(true);

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

数据绑定

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

// Have an initial data model. As Double is unmodificable and// doesn't support assignment from String, the object is// reconstructed in the wrapper when the value is changed.Double trouble = 42.0;// Wrap it in a property data sourcefinal ObjectProperty<Double> property =    new ObjectProperty<Double>(trouble);// Create a text field bound to itTextField tf = new TextField("The Answer", property);tf.setImmediate(true);// Show that the value is really written back to the// data source when edited by user.Label feedback = new Label(property);feedback.setCaption("The Value");

字符串长度

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

处理Null 值

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

比如:

// Create a text field without setting its valueTextField tf = new TextField("Field Energy (J)");tf.setNullRepresentation("-- null-point energy --");// The null value is actually the defaulttf.setValue(null);// Allow user to input the null value by// its representationtf.setNullSettingAllowed(true);// Feedback to see the valueLabel value = new Label(tf);value.setCaption("Current Value:");

结果如下:

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


 

 

 

 

 

原创粉丝点击