HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Vaadin / Vaadin Text Field Examples

Vaadin Text Field Examples

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

Table of Contents

Vaadin text field label
Vaadin text field width and height
Vaadin text field size limit
Vaadin text field focus
Vaadin text field change event listener
Vaadin text field empty validation
Vaadin text field number validation
Vaadin text field CSS styling
Source Code Download Link

Vaadin text field label

Vaadin text field label
Vaadin text field label

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

  1. Set text field label as constructor argument

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

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

Vaadin text field 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);

Vaadin text field size 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);

Vaadin text field focus

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

Vaadin text field change event listener

Vaadin text field change events
Vaadin text field change events

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

  1. 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);
    
  2. 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);
    

Vaadin text field empty 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.

Vaadin text field number validation

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

Vaadin text field CSS styling

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

Sourcecode Download

Click on below link to download the sourcecode of this project.

Download Sourcecode

Resources:

Vaadin Text Field Component
TextChangeListener
ValueChangeListener
StackOverflow

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Berend

    March 8, 2020

    Hi there

    If I would like the textbox size to be 100% of the screen width, how would I specify that?

Comments are closed on this article!

Search Tutorials

Vaadin Tutorial

  • Vaadin – Hello World Application
  • Vaadin – ComboBox
  • Vaadin – Text Field
  • Vaadin – Spring Security BasicAuth

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)