Vaadin Text Field Examples

Lokesh Gupta

Learn to setup, style, and validate Vaadin text field control with these simple-to-follow code examples.

Table of Contents

1. Vaadin text field label
2. Vaadin text field width and height
3. Vaadin text field size limit
4. Vaadin text field focus
5. Vaadin text field change event listener
6. Vaadin text field empty validation
7. Vaadin text field number validation
8. Vaadin text field CSS styling

1. Vaadin text field label

Vaadin text field label
Vaadin text field label

You can set the label for a text field in two ways.

  • Set text field label as constructor argument

    final TextField txtFldOne = new TextField("Type your name here:");
  • Set text field label using setCaption() method

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

2. Setting Width and Height

Vaadin text field size
Vaadin text field size

To set the text field’s width and height, use setXXX methods.

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);

//or

final TextField txtFldTwo = new TextField();
txtFldTwo.setCaption("Field size example 2");

txtFldTwo.setWidth("300px");
txtFldTwo.setHeight("50px");

layout.addComponents(txtFldTwo);

3. Setting Text Field Size and Limit

Vaadin text field limit
Vaadin text field limit

To set the maximum character limit in text field, use setMaxLength(int length) method.

final TextField txtFldOne = new TextField();
txtFldOne.setCaption("Field limit example");

txtFldOne.setMaxLength(10);

layout.addComponents(txtFldOne);

4. Setting Focus on Text Field

Vaadin text field focus
Vaadin text field focus

To bring the focus on the text field, use focus() method.

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

txtFldOne.focus();

layout.addComponents(txtFldOne);

5. Attach Event Listners on Text Fields

Vaadin text field change events
Vaadin text field change events

To handle any value change event in the text field, you can attach two event listeners.

  • Value change event listener

    Value change events are fired when there is a value change in text field, and when it looses focus after editing. handle value change events with 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);
    
  • Text change event listener

    Sometimes you may want to handle every text change event in text field as soon as it happens. You can handle these text changes using 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);
    

6. Empty Value Validation

Vaadin text field empty validation
Vaadin text field empty validation

To add empty field validation on a text field, use setRequired(), setRequiredError(), setValidationVisible() and add 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);

In above example, we are validating the text field on every key press event. If you want to validate the field only on focus off, then use ValueChangeEventListner.

7. Addinng Number Validation on Vaadin Text Fields

Vaadin text field number min-max validation
Vaadin text field number min-max validation
Vaadin text field number format validation
Vaadin text field number format validation

If you want to force a text field to accept only integer values, then you can use IntegerRangeValidator class and validate on text change events.

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
		}
	}
});

8. Styling Vaadin Text Fields

All text fields have style name v-textfield added to them so if you want any specific CSS to apply on all text fields then add it inside v-textfield class.

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

If you want to apply certain style on a single text field, then you can add the class name (e.g. darkBorder) to text field as below:

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

layout.addStyleName("darkBorder");

Now you can define the style rules in css file. Style name will be {.v-textfield + custom style class added to field}.

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

Complete Sourcecode

Now let’s see all above examples as written for this tutorial.

package com.howtodoinjava.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;
	}
}

Resources:

Vaadin Text Field Component
TextChangeListener
ValueChangeListener
StackOverflow

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode