Vaadin

Join Vaadin Log In

All components have a built-in error indicator that can be set explicitly with setComponentError() or can be turned on implicitly if validating the component fails. As with component caption, the placement of the indicator is managed by the layout in which the component is contained. Usually, the error indicator is placed right of the caption text. Hovering the mouse pointer over the field displays the error message.

The following example shows how you can set the component error explicitly. The example essentially validates field value without using an actual validator.

// Create a field.
final TextField textfield = new TextField("Enter code");
main.addComponent(textfield);
// Let the component error be initially clear.
textfield.setComponentError(null); // (actually the default)
// Have a button right of the field (and align it properly).
final Button button = new Button("Ok!");
main.addComponent(button);
((VerticalLayout)main.getLayout())
        .setComponentAlignment(button, Alignment.BOTTOM_LEFT);
// Handle button clicks
button.addListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        // If the field value is bad, set its error.
        // (Allow only alphanumeric characters.)
        if (! ((String) textfield.getValue()).matches("^\\w*$")) {
            // Put the component in error state and
            // set the error message.
            textfield.setComponentError(
                new UserError("Must be letters and numbers"));
        } else {
            // Otherwise clear it.
            textfield.setComponentError(null);
        }
    }
});

The Form component handles and displays also the errors of its contained fields so that it displays both the error indicator and the message in a special error indicator area. See Section 5.17, “Form and Section 5.17.3, “Validating Form Input” for details on the Form component and validation of form input.

Notifications are error or information boxes that appear typically at the center of the screen. A notification box has a caption and optional description and icon. The box stays on the screen either for a defined time or until the user clicks it. The notification type defines the default appearance and behaviour of a notification.

Notifications are always associated with a window object, which can be a child window (the positioning is always relative to the entire browser view). The Window class provides a showNotification() method for displaying notifications. The method takes the caption and an optional description and notification type as parameters. The method also accepts a notification object of type Window.Notification, as described further below.

mainwindow.showNotification("This is the caption",
                            "This is the description");

The caption and description are, by default, written on the same line. If you want to have a line break between them, use the XHTML line break markup "<br/>". You can use any XHTML markup in the caption and description of a notification. If it is possible to get the notification content from user input, you should sanitize the content carefully, as noted in Section 11.10.1, “Sanitizing User Input to Prevent Cross-Site Scripting”.

main.showNotification("This is a warning",
            "<br/>This is the <i>last</i> warning",
            Window.Notification.TYPE_WARNING_MESSAGE);

The notification type defines the overall default style and behaviour of a notification. If no notification type is given, the "humanized" type is used as the default. The notification types, listed below, are defined in the Window.Notification class.

TYPE_HUMANIZED_MESSAGE

A user-friendly message that does not annoy too much: it does not require confirmation by clicking and disappears quickly. It is centered and has a neutral gray color.

TYPE_WARNING_MESSAGE

Warnings are messages of medium importance. They are displayed with colors that are neither neutral nor too distractive. A warning is displayed for 1.5 seconds, but the user can click the message box to dismiss it. The user can continue to interact with the application while the warning is displayed.

TYPE_ERROR_MESSAGE

Error messages are notifications that require the highest user attention, with alert colors and by requiring the user to click the message to dismiss it. The error message box does not itself include an instruction to click the message, although the close box in the upper right corner indicates it visually. Unlike with other notifications, the user can not interact with the application while the error message is displayed.

TYPE_TRAY_NOTIFICATION

Tray notifications are displayed in the "system tray" area, that is, in the lower-right corner of the browser view. As they do not usually obsure any user interface, they are displayed longer than humanized or warning messages, 3 seconds by default. The user can continue to interact with the application normally while the tray notification is displayed.

All of the features of specific notification types can be controlled with the attributes of Window.Notification. You can pass an explicitly created notification object to the showNotification() method.

// Create a notification with default settings for a warning.
Window.Notification notif = new Window.Notification(
        "Be warned!",
        "This message lurks in the top-left corner!",
        Window.Notification.TYPE_WARNING_MESSAGE);
// Set the position.
notif.setPosition(Window.Notification.POSITION_TOP_LEFT);
// Let it stay there until the user clicks it
notif.setDelayMsec(-1);
// Show it in the main window.
main.showNotification(notif);

The setPosition() method allows setting the positioning of the notification. The method takes as its parameter any of the constants:

Window.Notification.POSITION_CENTERED 
Window.Notification.POSITION_CENTERED_TOP 
Window.Notification.POSITION_CENTERED_BOTTOM 
Window.Notification.POSITION_TOP_LEFT 
Window.Notification.POSITION_TOP_RIGHT 
Window.Notification.POSITION_BOTTOM_LEFT 
Window.Notification.POSITION_BOTTOM_RIGHT 

The setDelayMSec() allows you to set the time in milliseconds for how long the notification is displayed. Parameter value -1 means that the message is displayed until the user clicks the message box. It also prevents interaction with other parts of the application window, as is default behaviour for error messages. It does not, however, add a close box that the error notification has.

Application development with Vaadin follows the event-driven programming model. Mouse and keyboard events in the client cause (usually higher-level) events on the server-side, which can be handled with listeners, and that is how most of the application logic works. Handling the events can result in exceptions either in the application logic or in the framework itself, but some of them may not be caught properly.

For example, in the following code excerpt, we throw an error in an event listener but do not catch it, so it falls to the framework.

final Button button = new Button ("Fail Me");
button.addListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        // Throw some exception.
        throw new RuntimeException("You can't catch this.");
    }
});

Any such exceptions that occur in the call chain, but are not caught at any other level, are eventually caught by the terminal adapter in ApplicationServlet, the lowest-level component that receives client requests. The terminal adapter passes all such caught exceptions as events to the error listener of the Application instance through the Terminal.ErrorListener interface. The Application class does not, by default, throw such exceptions forward.

The reason for this error-handling logic lies in the logic that handles component state synchronization between the client and the server. We want to handle all the serialized variable changes in the client request, because otherwise the client-side and server-side component states would become unsynchronized very easily, which could put the entire application in an invalid state.

The default implementation of the Terminal.ErrorListener interface in the Application class simply prints the error to console. It also tries to find out a component related to the error. If the exception occurred in a listener attached to a component, that component is considered as the component related to the exception. If a related component is found, the error handler sets the component error for it, the same attribute which you can set with setComponentError().

In UI, the component error is shown with a small red "!" -sign (in the default theme). If you hover the mouse pointer over it, you will see the entire backtrace of the exception in a large tooltip box, as illustrated in Figure 4.9, “Uncaught Exception in Component Error Indicator” for the above code example.


You can change the logic of handling the terminal errors easily by overriding the terminalError() method in your application class (the one that inherits Application) or by setting a custom error listener with the setErrorHandler method. You can safely discard the default handling or extend its usage with your custom error handling or logging system. In the example code below, the exceptions are also reported as notifications in the main window.

@Override
public void terminalError(Terminal.ErrorEvent event) {
    // Call the default implementation.
    super.terminalError(event);
    // Some custom behaviour.
    if (getMainWindow() != null) {
        getMainWindow().showNotification(
                "An unchecked exception occured!",
                event.getThrowable().toString(),
                Notification.TYPE_ERROR_MESSAGE);
    }
}

Handling other exceptions works in the usual way for Java Servlets. Uncaught exceptions are finally caught and handled by the application server.

Table of Contents

Preface
1. Introduction
1.1. Overview
1.2. Example Application Walkthrough
1.3. Support for the Eclipse IDE
1.4. Goals and Philosophy
1.5. Background
2. Getting Started with Vaadin
2.1. Installing Vaadin
2.2. Setting up the Development Environment
2.3. QuickStart with Eclipse
2.4. Your First Project with Vaadin
3. Architecture
3.1. Overview
3.2. Technological Background
3.3. Applications as Java Servlet Sessions
3.4. Client-Side Engine
3.5. Events and Listeners
4. Writing a Web Application
4.1. Overview
4.2. Managing the Main Window
4.3. Child Windows
4.4. Handling Events with Listeners
4.5. Referencing Resources
4.6. Shutting Down an Application
4.7. Handling Errors
4.8. Setting Up the Application Environment
5. User Interface Components
5.1. Overview
5.2. Interfaces and Abstractions
5.3. Common Component Features
5.4. Label
5.5. Link
5.6. TextField
5.7. RichTextArea
5.8. Date and Time Input
5.9. Button
5.10. CheckBox
5.11. Selecting Items
5.12. Table
5.13. Tree
5.14. MenuBar
5.15. Embedded
5.16. Upload
5.17. Form
5.18. ProgressIndicator
5.19. Slider
5.20. Component Composition with CustomComponent
6. Managing Layout
6.1. Overview
6.2. Window and Panel Root Layout
6.3. VerticalLayout and HorizontalLayout
6.4. GridLayout
6.5. FormLayout
6.6. Panel
6.7. SplitPanel
6.8. TabSheet
6.9. Accordion
6.10. Layout Formatting
6.11. Custom Layouts
7. Visual User Interface Design with Eclipse (experimental)
7.1. Overview
7.2. Creating a New CustomComponent
7.3. Using The Visual Editor
7.4. Structure of a Visually Editable Component
8. Themes
8.1. Overview
8.2. Introduction to Cascading Style Sheets
8.3. Creating and Using Themes
8.4. Creating a Theme in Eclipse
9. Binding Components to Data
9.1. Overview
9.2. Properties
9.3. Holding properties in Items
9.4. Collecting items in Containers
10. Developing Custom Components
10.1. Overview
10.2. Doing It the Simple Way in Eclipse
10.3. Google Web Toolkit Widgets
10.4. Integrating a GWT Widget
10.5. Defining a Widget Set
10.6. Server-Side Components
10.7. Using a Custom Component
10.8. GWT Widget Development
11. Advanced Web Application Topics
11.1. Special Characteristics of AJAX Applications
11.2. Application-Level Windows
11.3. Embedding Applications in Web Pages
11.4. Debug and Production Mode
11.5. Resources
11.6. Shortcut Keys
11.7. Printing
11.8. Portal Integration
11.9. Google App Engine Integration
11.10. Common Security Issues
11.11. URI Fragment and History Management with UriFragmentUtility
11.12. Capturing HTTP Requests
A. User Interface Definition Language (UIDL)
A.1. API for Painting Components
A.2. JSON Rendering
B. Songs of Vaadin
Index