Handling Errors- Vaadin Applications
Handling Errors is very important in every application.This ensures that the application runs smoothly and users are notified incase the data they submit is not valid.For example,think of a field where the user is required to enter a email,if he/she adds firstname,the application should notify the user error made.
Handling Errors ensures data integrity and validity.Handling Errors in vaadin application can be done by using built in functions added in a components.This can be declared by setting component error
Handling Errors
1.Error indicator and Message
Run below code in your eclipse IDE.
package com.example.writers; import com.vaadin.Application; import com.vaadin.terminal.UserError; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.TextField; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.Window.CloseEvent; /** * Main application class. */ public class WritersApplication extends Application { Window mainWindow;//defining new variables TextField field;//defining textfield variable Button register;//register button ForgotPassword forgot; @Override public void init() { mainWindow = new Window("Closing Window application");//Application main Window.All other subwindows will be added here field= new TextField("Enter Code");//creating new textfield field.setComponentError(null);//setting error component mainWindow.addComponent(field);//adding textfield to the mainwindow register=new Button("Register");//creating register button register.addListener(new Button.ClickListener()//adding listener to the button { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub if (!((String)field.getValue()).matches("^\\w*$"))// if user enters one of these characters error is displayed { field.setComponentError( new UserError("Must be letters"));//error message } else{ field.setComponentError(null);//incase user enters letters or numbers no error to be displayed } } }); mainWindow.addComponent(register);//add button to the mainwindow ((VerticalLayout)mainWindow.getLayout()) .setComponentAlignment(register, Alignment.BOTTOM_LEFT); setMainWindow(mainWindow);//setting mainwindow } }
After running above code,You should be able to see result in the captioned image below.
Above code introduces some very new methods.setComponentError( new UserError(“Must be letters”)) method is responsible for displaying error when the user enters other characters that are not letters or numbers.
Forms in Vaadin have a special way of displaying errors.The fields in the form all have error indicator field and also a special message in a error indicator area.