原文: https://howtodoinjava.com/vaadin/vaadin-text-field-examples/

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

  1. Table of Contents
  2. Vaadin text field label
  3. Vaadin text field width and height
  4. Vaadin text field size limit
  5. Vaadin text field focus
  6. Vaadin text field change event listener
  7. Vaadin text field empty validation
  8. Vaadin text field number validation
  9. Vaadin text field CSS styling
  10. Source Code Download Link

Vaadin 文本字段标签

vaadin 文本字段示例 - 图1

Vaadin 文本字段标签

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

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

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

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

Vaadin 文本字段的宽度和高度

vaadin 文本字段示例 - 图2

Vaadin 文本字段大小

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

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

或者

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

Vaadin 文本字段大小限制

vaadin 文本字段示例 - 图3

Vaadin 文本字段限制

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

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

Vaadin 文本字段焦点

vaadin 文本字段示例 - 图4

Vaadin 文本字段焦点

要使焦点集中在文本字段上,请使用focus()方法。

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

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

vaadin 文本字段示例 - 图5

Vaadin 文本字段更改事件

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

  1. 值更改事件监听器


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

  1. final TextField txtFld = new TextField();
  2. txtFld.setCaption("Field value change listner example");
  3. txtFld.focus();
  4. txtFld.setInputPrompt("Enter any text");
  5. txtFld.addValueChangeListener(new Property.ValueChangeListener()
  6. {
  7. private static final long serialVersionUID = 5678485350989070188L;
  8. public void valueChange(ValueChangeEvent event)
  9. {
  10. String value = (String) event.getProperty().getValue();
  11. // Do something with the value. I am showing a tray notification
  12. Notification.show("Value is: " + value, Type.TRAY_NOTIFICATION);
  13. }
  14. });
  15. //Fire value changes immediately when the field loses focus
  16. txtFld.setImmediate(true);
  17. layout.addComponents(txtFld);
  1. 文本更改事件监听器


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

  1. final TextField txtFld = new TextField();
  2. txtFld.setCaption("Field text change listner example");
  3. txtFld.focus();
  4. txtFld.setMaxLength(20);
  5. txtFld.setInputPrompt("Enter any text");
  6. final Label counter = new Label();
  7. counter.setValue(txtFld.getValue().length() + " of " + txtFld.getMaxLength());
  8. txtFld.addTextChangeListener(new TextChangeListener() {
  9. private static final long serialVersionUID = -8043238443902618783L;
  10. public void textChange(TextChangeEvent event) {
  11. counter.setValue(event.getText().length() + " of " + txtFld.getMaxLength());
  12. }
  13. });
  14. txtFld.setTextChangeEventMode(TextChangeEventMode.EAGER);
  15. layout.addComponents(txtFld);
  16. layout.addComponents(counter);

Vaadin 文本字段空验证

vaadin 文本字段示例 - 图6

Vaadin 文本字段空验证

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

  1. final TextField txtFld = new TextField();
  2. txtFld.setCaption("Empty field validation example");
  3. txtFld.setInputPrompt("Enter your name");
  4. txtFld.setRequired(true);
  5. txtFld.setRequiredError("Please enter your name to proceed !!");
  6. txtFld.addValidator(new StringLengthValidator("Must be less than 20 chars", 1, 20, false));
  7. txtFld.setValidationVisible(true);
  8. txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
  9. txtFld.setNullRepresentation("");
  10. txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
  11. private static final long serialVersionUID = 1L;
  12. @Override
  13. public void textChange(FieldEvents.TextChangeEvent event) {
  14. try {
  15. txtFld.setValue(event.getText());
  16. txtFld.setCursorPosition(event.getCursorPosition());
  17. txtFld.validate();
  18. } catch (InvalidValueException e) {
  19. //Log error
  20. }
  21. }
  22. });
  23. layout.addComponents(txtFld);

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

Vaadin 文本字段数字验证

vaadin 文本字段示例 - 图7

Vaadin 文本字段数字最大最小验证

vaadin 文本字段示例 - 图8

Vaadin 文本字段数字格式验证

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

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

Vaadin 文本字段 CSS 样式

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

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

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

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

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

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

完整的源代码

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

  1. package com.howtodoinjava.vaadin.demo;
  2. import com.vaadin.annotations.Theme;
  3. import com.vaadin.annotations.VaadinServletConfiguration;
  4. import com.vaadin.data.Property;
  5. import com.vaadin.data.Property.ValueChangeEvent;
  6. import com.vaadin.data.Validator.InvalidValueException;
  7. import com.vaadin.data.util.converter.StringToIntegerConverter;
  8. import com.vaadin.data.validator.IntegerRangeValidator;
  9. import com.vaadin.data.validator.StringLengthValidator;
  10. import com.vaadin.event.FieldEvents;
  11. import com.vaadin.event.FieldEvents.TextChangeEvent;
  12. import com.vaadin.event.FieldEvents.TextChangeListener;
  13. import com.vaadin.server.VaadinRequest;
  14. import com.vaadin.server.VaadinServlet;
  15. import com.vaadin.ui.AbstractTextField.TextChangeEventMode;
  16. import com.vaadin.ui.Label;
  17. import com.vaadin.ui.Notification;
  18. import com.vaadin.ui.Notification.Type;
  19. import com.vaadin.ui.TextField;
  20. import com.vaadin.ui.UI;
  21. import com.vaadin.ui.VerticalLayout;
  22. @Theme("mytheme")
  23. public class MyUI extends UI {
  24. private static final long serialVersionUID = 1387172685749279538L;
  25. @Override
  26. protected void init(VaadinRequest vaadinRequest) {
  27. final VerticalLayout layout = new VerticalLayout();
  28. fieldLabelExample(layout);
  29. fieldSizeExample(layout);
  30. fieldLimitExample(layout);
  31. fieldFocusExample(layout);
  32. fieldValueChangeListenerExample(layout);
  33. fieldTextChangeListenerExample(layout);
  34. fieldNullValidationExample(layout);
  35. fieldNumberValidationExample(layout);
  36. customCSSExample(layout);
  37. layout.setMargin(true);
  38. layout.setSpacing(true);
  39. setContent(layout);
  40. }
  41. private void customCSSExample(VerticalLayout layout) {
  42. final TextField txtFld = new TextField("Custom Styled Text Box");
  43. layout.addComponent(txtFld);
  44. layout.addStyleName("darkBorder");
  45. }
  46. private void fieldNumberValidationExample(VerticalLayout layout) {
  47. final TextField txtFld = new TextField("Please enter only integer value");
  48. layout.addComponent(txtFld);
  49. //To convert string value to integer before validation
  50. txtFld.setConverter(new StringToIntegerConverter());
  51. //Add error message and min-max values allowed in field. If no limit than use null
  52. txtFld.addValidator(new IntegerRangeValidator("The value must be between 0 and 100", 0, 100));
  53. //What if text field is empty - integer will be null in that case, so show blank when null
  54. txtFld.setNullRepresentation("");
  55. //Add validation hints in UI??
  56. txtFld.setValidationVisible(true);
  57. txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
  58. txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
  59. private static final long serialVersionUID = 1L;
  60. @Override
  61. public void textChange(FieldEvents.TextChangeEvent event) {
  62. try {
  63. txtFld.setCursorPosition(event.getCursorPosition());
  64. txtFld.validate();
  65. } catch (InvalidValueException e) {
  66. //Log error
  67. }
  68. }
  69. });
  70. }
  71. private void fieldNullValidationExample(VerticalLayout layout) {
  72. final TextField txtFld = new TextField();
  73. txtFld.setCaption("Empty field validation example");
  74. txtFld.setInputPrompt("Enter your name");
  75. txtFld.setRequired(true);
  76. txtFld.setRequiredError("Please enter your name to proceed !!");
  77. txtFld.addValidator(new StringLengthValidator("Must be less than 20 chars", 1, 20, false));
  78. txtFld.setValidationVisible(true);
  79. txtFld.setTextChangeEventMode(TextChangeEventMode.LAZY);
  80. txtFld.setNullRepresentation("");
  81. txtFld.addTextChangeListener(new FieldEvents.TextChangeListener() {
  82. private static final long serialVersionUID = 1L;
  83. @Override
  84. public void textChange(FieldEvents.TextChangeEvent event) {
  85. try {
  86. txtFld.setValue(event.getText());
  87. txtFld.setCursorPosition(event.getCursorPosition());
  88. txtFld.validate();
  89. } catch (InvalidValueException e) {
  90. //Log error
  91. }
  92. }
  93. });
  94. layout.addComponents(txtFld);
  95. }
  96. private void fieldTextChangeListenerExample(VerticalLayout layout) {
  97. final TextField txtFld = new TextField();
  98. txtFld.setCaption("Field text change listner example");
  99. txtFld.focus();
  100. txtFld.setMaxLength(20);
  101. txtFld.setInputPrompt("Enter any text");
  102. final Label counter = new Label();
  103. counter.setValue(txtFld.getValue().length() + " of " + txtFld.getMaxLength());
  104. txtFld.addTextChangeListener(new TextChangeListener() {
  105. private static final long serialVersionUID = -8043238443902618783L;
  106. public void textChange(TextChangeEvent event) {
  107. counter.setValue(event.getText().length() + " of "
  108. + txtFld.getMaxLength());
  109. }
  110. });
  111. txtFld.setTextChangeEventMode(TextChangeEventMode.EAGER);
  112. layout.addComponents(txtFld);
  113. layout.addComponents(counter);
  114. }
  115. private void fieldValueChangeListenerExample(VerticalLayout layout) {
  116. final TextField txtFld = new TextField();
  117. txtFld.setCaption("Field value change listner example");
  118. txtFld.focus();
  119. txtFld.setInputPrompt("Enter any text");
  120. txtFld.addValueChangeListener(new Property.ValueChangeListener() {
  121. private static final long serialVersionUID = 5678485350989070188L;
  122. public void valueChange(ValueChangeEvent event) {
  123. String value = (String) event.getProperty().getValue();
  124. // Do something with the value
  125. Notification.show("Value is: " + value, Type.TRAY_NOTIFICATION);
  126. }
  127. });
  128. // Fire value changes immediately when the field loses focus
  129. txtFld.setImmediate(true);
  130. layout.addComponents(txtFld);
  131. }
  132. private void fieldFocusExample(VerticalLayout layout) {
  133. final TextField txtFld = new TextField();
  134. txtFld.setCaption("Field focus example");
  135. txtFld.focus();
  136. layout.addComponents(txtFld);
  137. }
  138. private void fieldLimitExample(VerticalLayout layout) {
  139. final TextField txtFld = new TextField();
  140. txtFld.setCaption("Field limit example");
  141. txtFld.setMaxLength(10);
  142. layout.addComponents(txtFld);
  143. }
  144. private void fieldSizeExample(VerticalLayout layout) {
  145. final TextField txtFldOne = new TextField();
  146. txtFldOne.setCaption("Field size example 1");
  147. txtFldOne.setWidth(300, Unit.PIXELS);
  148. txtFldOne.setHeight(50, Unit.PIXELS);
  149. final TextField txtFldTwo = new TextField();
  150. txtFldTwo.setCaption("Field size example 2");
  151. txtFldTwo.setWidth("300px");
  152. txtFldTwo.setHeight("50px");
  153. layout.addComponents(txtFldOne);
  154. layout.addComponents(txtFldTwo);
  155. }
  156. private void fieldLabelExample(VerticalLayout layout) {
  157. final TextField txtFld = new TextField();
  158. // Set Text Field Label
  159. txtFld.setCaption("Type your name here:");
  160. layout.addComponents(txtFld);
  161. }
  162. @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
  163. public static class MyUIServlet extends VaadinServlet {
  164. private static final long serialVersionUID = -2718268186398688122L;
  165. }
  166. }

源代码下载

单击下面的链接下载该项目的源代码。

下载源码

资源:

Vaadin 文本字段组件

TextChangeListener

ValueChangeListener

StackOverflow