Vaadin文本字段示例

学习这些简单易懂的代码示例,以设置,设置样式和验证vaadin文本字段控件。

目录

Vaadin文本字段标签
Vaadin文本字段的宽度和高度
Vaadin文本字段的大小限制
Vaadin文本字段的焦点
Vaadin文本字段更改事件侦听器
Vaadin文本字段为空验证
Vaadin文本字段编号为验证
Vaadin文本字段CSS样式
源代码下载链接

Vaadin文本字段标签

Vaadin文本字段标签
Vaadin文本字段标签

您可以通过两种方式为文本字段设置标签。

  1. 将文本字段标签设置为构造函数参数

    final TextField txtFldOne = new TextField("Type your name here:");
  2. 使用setCaption()方法设置文本字段标签

    final TextField txtFldOne = new TextField();
    //Set Text Field Label
    txtFldOne.setCaption("Type your name here:");

Vaadin文本字段的宽度和高度

Vaadin文字栏位大小
Vaadin文字栏位大小

若要设置文本字段的宽度和高度,请使用setXXX方法。

final TextField txtFldOne = new TextField();
txtFldOne.setCaption("Field size example 1");
//Set width and height
txtFldOne.setWidth(300, Unit.PIXELS);
txtFldOne.setHeight(50, Unit.PIXELS);
layout.addComponents(txtFldOne);

//要么

final TextField txtFldTwo = new TextField();
txtFldTwo.setCaption("Field size example 2");
txtFldTwo.setWidth("300px");
txtFldTwo.setHeight("50px");
layout.addComponents(txtFldTwo);

Vaadin文字栏位大小限制

Vaadin文字栏位限制
Vaadin文字栏位限制

要在文本字段中设置最大字符数限制,请使用setMaxLength(int length)方法。

final TextField txtFldOne = new TextField();
txtFldOne.setCaption("Field limit example");
txtFldOne.setMaxLength(10);
layout.addComponents(txtFldOne);

Vaadin文本字段焦点

Vaadin文本字段焦点
Vaadin文本字段焦点

若要将重点放在文本字段上,请使用focus()方法。

final TextField txtFldOne = new TextField();
txtFldOne.setCaption("Field focus example");
txtFldOne.focus();
layout.addComponents(txtFldOne);

Vaadin文本字段更改事件侦听器

Vaadin文本字段更改事件
Vaadin文本字段更改事件

要处理文本字段中的任何值更改事件,您可以附加两个事件侦听器。

  1. 值更改事件侦听器

    当文本字段中发生值更改,并且在编辑后失去焦点时,将触发值更改事件。使用来处理价值变更事件ValueChangeListener

    final TextField txtFld = new TextField();
    txtFld.setCaption("Field value change listner example");
    txtFld.focus();
    txtFld.setInputPrompt("Enter any text");
    txtFld.addValueChangeListener(new Property.ValueChangeListener()
    {
        private static final long serialVersionUID = 5678485350989070188L;
        public void valueChange(ValueChangeEvent event)
        {
            String value = (String) event.getProperty().getValue();
            // Do something with the value. I am showing a tray notification
            Notification.show("Value is: " + value, Type.TRAY_NOTIFICATION);
        }
    });
    //Fire value changes immediately when the field loses focus
    txtFld.setImmediate(true);
    layout.addComponents(txtFld);
  2. 文字变更事件监听器

    有时,您可能希望尽快处理文本字段中的每个文本更改事件。您可以使用来处理这些文本更改TextChangeListener

    final TextField txtFld = new TextField();
    txtFld.setCaption("Field text change listner example");
    txtFld.focus();
    txtFld.setMaxLength(20);
    txtFld.setInputPrompt("Enter any text");
    final Label counter = new Label();
    counter.setValue(txtFld.getValue().length() + " of " + txtFld.getMaxLength());
    txtFld.addTextChangeListener(new TextChangeListener() {
        private static final long serialVersionUID = -8043238443902618783L;
        public void textChange(TextChangeEvent event) {
            counter.setValue(event.getText().length() + " of " + txtFld.getMaxLength());
        }
    });
    txtFld.setTextChangeEventMode(TextChangeEventMode.EAGER);
    layout.addComponents(txtFld);
    layout.addComponents(counter);

Vaadin文本字段为空验证

Vaadin文本字段为空验证
Vaadin文本字段为空验证

要在文本字段,使用添加空字段验证setRequired()setRequiredError()setValidationVisible()和添加StringLengthValidator

final TextField txtFld = new TextField();
txtFld.setCaption("Empty field validation example");
txtFld.setInputPrompt("Enter your name");
txtFld.setRequired(true);
txtFld.setRequiredError("Please enter your name to proceed !!");
txtFld.addValidator(new StringLengthValidator("Must be less than 20 chars", 1, 20, false));
txtFld.setValidationVisible(true);
txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
txtFld.setNullRepresentation("");
txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
    private static final long serialVersionUID = 1L;
    @Override
    public void textChange(FieldEvents.TextChangeEvent event) {
        try {
            txtFld.setValue(event.getText());
            txtFld.setCursorPosition(event.getCursorPosition());
            txtFld.validate();
        } catch (InvalidValueException e) {
            //Log error
        }
    }
});
layout.addComponents(txtFld);

在上面的示例中,我们在每个按键事件上验证文本字段。如果您只想重点关注验证字段,请使用ValueChangeEventListner

Vaadin文本字段编号验证

Vaadin文本字段编号最小-最大验证
Vaadin文本字段编号最小-最大验证
Vaadin文本字段数字格式验证
Vaadin文本字段数字格式验证

如果要强制文本字段仅接受整数值,则可以使用IntegerRangeValidatorclass并针对文本更改事件进行验证。

final TextField txtFld = new TextField("Please enter only integer value");
layout.addComponent(txtFld);
//To convert string value to integer before validation
txtFld.setConverter(new StringToIntegerConverter());
//Add error message and min-max values allowed in field. If no limit than use null
txtFld.addValidator(new IntegerRangeValidator("The value has to be an integer", null, null));
//What if text field is empty - integer will be null in that case, so show blank when null
txtFld.setNullRepresentation("");
//Add validation hints in UI??
txtFld.setValidationVisible(true);
txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
    private static final long serialVersionUID = 1L;
    @Override
    public void textChange(FieldEvents.TextChangeEvent event) {
        try {
            txtFld.setCursorPosition(event.getCursorPosition());
            txtFld.validate();
        } catch (InvalidValueException e) {
            //Log error
        }
    }
});

Vaadin文本字段CSS样式

所有文本字段均v-textfield添加了样式名称,因此,如果您希望将特定的CSS应用于所有文本字段,则将其添加到v-textfield类中。

.v-textfield {
    //style to apply on all text fields
}

如果要在单个文本字段上应用某种样式,则可以将类名称(例如darkBorder)添加到文本字段,如下所示:

final TextField txtFld = new TextField("Custom Styled Text Box");
layout.addComponent(txtFld);
layout.addStyleName("darkBorder");

现在,您可以在css文件中定义样式规则。样式名称将为{.v-textfield +自定义样式类添加到字段}。

.v-textfield-darkBorder {
    border: 5px solid gray;
}

完整的源代码

现在,让我们看看上面为本教程编写的所有示例。

package com.how2codex.vaadin.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.converter.StringToIntegerConverter;
import com.vaadin.data.validator.IntegerRangeValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.event.FieldEvents;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.AbstractTextField.TextChangeEventMode;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
    private static final long serialVersionUID = 1387172685749279538L;
    @Override
    protected void init(VaadinRequest vaadinRequest) {
        final VerticalLayout layout = new VerticalLayout();
        fieldLabelExample(layout);
        fieldSizeExample(layout);
        fieldLimitExample(layout);
        fieldFocusExample(layout);
        fieldValueChangeListenerExample(layout);
        fieldTextChangeListenerExample(layout);
        fieldNullValidationExample(layout);
        fieldNumberValidationExample(layout);
        customCSSExample(layout);
        layout.setMargin(true);
        layout.setSpacing(true);
        setContent(layout);
    }
    
    private void customCSSExample(VerticalLayout layout) {
        final TextField txtFld = new TextField("Custom Styled Text Box");
        layout.addComponent(txtFld);
        
        layout.addStyleName("darkBorder");
    }
    
    private void fieldNumberValidationExample(VerticalLayout layout) {
        
        final TextField txtFld = new TextField("Please enter only integer value");
        layout.addComponent(txtFld);
        
        //To convert string value to integer before validation
        txtFld.setConverter(new StringToIntegerConverter());
        
        //Add error message and min-max values allowed in field. If no limit than use null
        txtFld.addValidator(new IntegerRangeValidator("The value must be between 0 and 100", 0, 100));
        
        //What if text field is empty - integer will be null in that case, so show blank when null
        txtFld.setNullRepresentation("");
        
        //Add validation hints in UI??
        txtFld.setValidationVisible(true);
        
        txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
        
        txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
            private static final long serialVersionUID = 1L;
            @Override
            public void textChange(FieldEvents.TextChangeEvent event) {
                try {
                    txtFld.setCursorPosition(event.getCursorPosition());
                    txtFld.validate();
                } catch (InvalidValueException e) {
                    //Log error
                }
            }
        });
    }
    private void fieldNullValidationExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        txtFld.setCaption("Empty field validation example");
        txtFld.setInputPrompt("Enter your name");
        txtFld.setRequired(true);
        txtFld.setRequiredError("Please enter your name to proceed !!");
        txtFld.addValidator(new StringLengthValidator("Must be less than 20 chars", 1, 20, false));
        txtFld.setValidationVisible(true);
        txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
        txtFld.setNullRepresentation("");
        txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
            private static final long serialVersionUID = 1L;
            @Override
            public void textChange(FieldEvents.TextChangeEvent event) {
                try {
                    txtFld.setValue(event.getText());
                    txtFld.setCursorPosition(event.getCursorPosition());
                    txtFld.validate();
                } catch (InvalidValueException e) {
                    //Log error
                }
            }
        });
        layout.addComponents(txtFld);
    }
    private void fieldTextChangeListenerExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        txtFld.setCaption("Field text change listner example");
        txtFld.focus();
        txtFld.setMaxLength(20);
        txtFld.setInputPrompt("Enter any text");
        final Label counter = new Label();
        counter.setValue(txtFld.getValue().length() + " of " + txtFld.getMaxLength());
        txtFld.addTextChangeListener(new TextChangeListener() {
            private static final long serialVersionUID = -8043238443902618783L;
            public void textChange(TextChangeEvent event) {
                counter.setValue(event.getText().length() + " of "
                        + txtFld.getMaxLength());
            }
        });
        txtFld.setTextChangeEventMode(TextChangeEventMode.EAGER);
        layout.addComponents(txtFld);
        layout.addComponents(counter);
    }
    private void fieldValueChangeListenerExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        txtFld.setCaption("Field value change listner example");
        txtFld.focus();
        txtFld.setInputPrompt("Enter any text");
        txtFld.addValueChangeListener(new Property.ValueChangeListener() {
            private static final long serialVersionUID = 5678485350989070188L;
            public void valueChange(ValueChangeEvent event) {
                String value = (String) event.getProperty().getValue();
                // Do something with the value
                Notification.show("Value is: " + value, Type.TRAY_NOTIFICATION);
            }
        });
        // Fire value changes immediately when the field loses focus
        txtFld.setImmediate(true);
        layout.addComponents(txtFld);
    }
    private void fieldFocusExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        txtFld.setCaption("Field focus example");
        txtFld.focus();
        layout.addComponents(txtFld);
    }
    private void fieldLimitExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        txtFld.setCaption("Field limit example");
        txtFld.setMaxLength(10);
        layout.addComponents(txtFld);
    }
    private void fieldSizeExample(VerticalLayout layout) {
        final TextField txtFldOne = new TextField();
        txtFldOne.setCaption("Field size example 1");
        txtFldOne.setWidth(300, Unit.PIXELS);
        txtFldOne.setHeight(50, Unit.PIXELS);
        final TextField txtFldTwo = new TextField();
        txtFldTwo.setCaption("Field size example 2");
        txtFldTwo.setWidth("300px");
        txtFldTwo.setHeight("50px");
        layout.addComponents(txtFldOne);
        layout.addComponents(txtFldTwo);
    }
    private void fieldLabelExample(VerticalLayout layout) {
        final TextField txtFld = new TextField();
        // Set Text Field Label
        txtFld.setCaption("Type your name here:");
        layout.addComponents(txtFld);
    }
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
    public static class MyUIServlet extends VaadinServlet {
        private static final long serialVersionUID = -2718268186398688122L;
    }
}

 

saigon has written 1440 articles

Leave a Reply