Vaadin

Join Vaadin Log In

The component base classes and interfaces provide a large number of features. Let us look at some of the most commonly needed features. Features not documented here can be found from the Java API Reference.

The interface defines a number of properties, which you can retrieve or manipulate with the corresponding setters and getters.

A caption is an explanatory textual label accompanying a user interface component, usually shown above, left of, or inside the component. The contents of a caption are automatically quoted, so no raw XHTML can be rendered in a caption.

The caption can usually be given as the first parameter of a constructor or later with the setCaption() method.

// New text field with caption "Name"
TextField name = new TextField("Name");
layout.addComponent(name);

The caption of a component is, by default, managed and displayed by the layout component or component container in which the component is placed. For example, the VerticalLayout component shows the captions left-aligned above the contained components, while the FormLayout component shows the captions on the left side of the vertically laid components, with the captions and their associated components left-aligned in their own columns. The CustomComponent does not manage the caption of its composition root, so if the root component has a caption, it will not be rendered.


Some components, such as Button and Panel, manage the caption themselves and display it inside the component.

Icon (see Section 5.3.4, “Icon”) is closely related to caption and is usually displayed horizontally before or after it, depending on the component and the containing layout.

An alternative way to implement a caption is to use another component as the caption, typically a Label, a TextField, or a Panel. A Label, for example, allows highlighting a shortcut key with XHTML markup or to bind the caption to a data source. The Panel provides an easy way to add both a caption and a border around a component.

Setting the caption with setCaption() will cause updating the component. A reimplementation of setCaption() should call the superclass implementation.

All components (that inherit AbstractComponent) have a description separate from their caption. The description is usually shown as a tooltip that appears when the mouse pointer hovers over the component for a short time.

You can set the description with setDescription() and retrieve with getDescription().

Button button = new Button("A Button");
button.setDescription("This is the tooltip");

The tooltip is shown in Figure 5.6, “Component Description as a Tooltip”.


A description is rendered as a tooltip in most components. Form shows it as text in the top area of the component, as described in Section 5.17.1, “Form as a User Interface Component”.

When a component error has been set with setComponentError(), the error is usually also displayed in the tooltip, below the description (Form displays it in the bottom area of the form). Components that are in error state will also display the error indicator. See Section 4.7.1, “Error Indicator and message”.

The description is actually not plain text, but you can use XHTML tags to format it. Such a rich text description can contain any HTML elements, including images.

button.setDescription(
    "<h2><img src=\"../VAADIN/themes/sampler/icons/comment_yellow.gif\"/>"+
    "A richtext tooltip</h2>"+
    "<ul>"+
    "  <li>Use rich formatting with XHTML</li>"+
    "  <li>Include images from themes</li>"+
    "  <li>etc.</li>"+
    "</ul>");

The result is shown in Figure 5.7, “A Rich Text Tooltip”.


Notice that the setter and getter are defined for all fields in the Field interface, not for all components in the Component interface.

An icon is an explanatory graphical label accompanying a user interface component, usually shown above, left of, or inside the component. Icon is closely related to caption (see Section 5.3.1, “Caption”) and is usually displayed horizontally before or after it, depending on the component and the containing layout.

The icon of a component can be set with the setIcon() method. The image is provided as a resource, perhaps most typically a ThemeResource.

// Component with an icon from a custom theme
TextField name = new TextField("Name");
name.setIcon(new ThemeResource("icons/user.png"));
layout.addComponent(name);
        
// Component with an icon from another theme ('runo')
Button ok = new Button("OK");
ok.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
layout.addComponent(ok);

The icon of a component is, by default, managed and displayed by the layout component or component container in which the component is placed. For example, the VerticalLayout component shows the icons left-aligned above the contained components, while the FormLayout component shows the icons on the left side of the vertically laid components, with the icons and their associated components left-aligned in their own columns. The CustomComponent does not manage the icon of its composition root, so if the root component has an icon, it will not be rendered.


Some components, such as Button and Panel, manage the icon themselves and display it inside the component.

The locale property defines the country and language used in a component. You can use the locale information in conjunction with an internationalization scheme to acquire localized resources. Some components, such as DateField, use the locale for component localization.

You can set the locale of a component (or the application) with setLocale().

// Component for which the locale is meaningful
InlineDateField date = new InlineDateField("Datum");
        
// German language specified with ISO 639-1 language
// code and ISO 3166-1 alpha-2 country code. 
date.setLocale(new Locale("de", "DE"));
        
date.setResolution(DateField.RESOLUTION_DAY);
layout.addComponent(date);

The resulting date field is shown in Figure 5.11, “Set Locale for InlineDateField.


You can get the locale of a component with getLocale(). If the locale is undefined for a component, that is, not explicitly set, the locale of the parent component is used. If none of the parent components have a locale set, the locale of the application is used, and if that is not set, the default system locale is set, as given by Locale.getDefault().

Because of the requirement that the component must be attached to the application, it is awkward to use getLocale() for internationalization. You can not use it in the constructor, so you would have to get the locale in attach() as shown in the following example:

Button cancel = new Button() {
    @Override
    public void attach() {
        ResourceBundle bundle = ResourceBundle.getBundle(
                MyAppCaptions.class.getName(), getLocale());
        setCaption(bundle.getString("CancelKey"));
    }
};
layout.addComponent(cancel);

It is normally a better practice to get the locale from an application-global parameter and use it to get the localized resource right when the component is created.

// Captions are stored in MyAppCaptions resource bundle
// and the application object is known in this context.
ResourceBundle bundle =
    ResourceBundle.getBundle(MyAppCaptions.class.getName(),
                             getApplication().getLocale());
        
// Get a localized resource from the bundle
Button cancel = new Button(bundle.getString("CancelKey"));
layout.addComponent(cancel);

A common task in many applications is selecting a locale. This is done in the following example with a Select component.

// The locale in which we want to have the language
// selection list
Locale displayLocale = Locale.ENGLISH;
        
// All known locales
final Locale[] locales = Locale.getAvailableLocales();
        
// Allow selecting a language. We are in a constructor of a
// CustomComponent, so preselecting the current
// language of the application can not be done before
// this (and the selection) component are attached to
// the application.
final Select select = new Select("Select a language") {
    @Override
    public void attach() {
        setValue(getLocale());
    }
};
for (int i=0; i<locales.length; i++) {
    select.addItem(locales[i]);
    select.setItemCaption(locales[i],
                          locales[i].getDisplayName(displayLocale));
    
    // Automatically select the current locale
    if (locales[i].equals(getLocale()))
        select.setValue(locales[i]);
}
layout.addComponent(select);
// Locale code of the selected locale
final Label localeCode = new Label("");
layout.addComponent(localeCode);
// A date field which language the selection will change
final InlineDateField date =
    new InlineDateField("Calendar in the selected language");
date.setResolution(DateField.RESOLUTION_DAY);
layout.addComponent(date);
        
// Handle language selection
select.addListener(new Property.ValueChangeListener() {
    public void valueChange(ValueChangeEvent event) {
        Locale locale = (Locale) select.getValue();
        date.setLocale(locale);
        localeCode.setValue("Locale code: " +
                            locale.getLanguage() + "_" +
                            locale.getCountry());
    }
});
select.setImmediate(true);

The user interface is shown in Figure 5.12, “Selecting a Locale”.


The property defines whether the user can change the value of a component. As only Field components have a value that can be input or edited by the user, this method is mainly applicable to field components. The read-only property does not prevent changing the value of a component programmatically.

TextField readwrite = new TextField("Read-Write");
readwrite.setValue("You can change this");
readwrite.setReadOnly(false); // The default
layout.addComponent(readwrite);
        
TextField readonly = new TextField("Read-Only");
readonly.setValue("You can't touch this!");
readonly.setReadOnly(true);
layout.addComponent(readonly);

The resulting read-only text field is shown in Figure 5.13, “A Read-Only Component.”.


Even when a component is read-only, the user may be able to interact with some component features, such as scrolling.

Client-side state modifications will not be communicated to the server-side and, more important, server-side field components will not accept changes to the value of a read-only component. This is an important security feature, because a malicious user can not fabricate state changes in a read-only component. Notice that this occurs at the level of AbstractField in setValue() and therefore only applies to the property value of the component; a component could itself accept some variable changes from the client-side.

Components can be hidden by setting the visible property to false. Also the caption, icon and any other component features are made hidden. Hidden components are not just invisible, but their content is not communicated to the browser at all. That is, they are not made invisible cosmetically with only CSS rules. This feature is important for security if you have components that contain security-critical information that must only be shown in specific application states.

TextField readonly = new TextField("Read-Only");
readonly.setValue("You can't see this!");
readonly.setVisible(false);
layout.addComponent(readonly);

The resulting invisible component is shown in Figure 5.15, “An Invisible Component.”.


If you need to make a component only cosmetically invisible, you should use a custom theme to set it display: none style. This is mainly useful for certain special components such as ProgressIndicator, which have effects even when made invisible in CSS. If the hidden component has undefined size and is enclosed in a layout that also has undefined size, the containing layout will collapse when the component disappears. If you want to have the component keep its size, you have to make it invisible by setting all its font and other attributes to be transparent. In such cases, the invisible content of the component can be made visible easily in the browser.

An invisible component has no particular CSS style class to indicate that it is hidden. The element does exist though, but has display: none style, which overrides any CSS styling.

Vaadin components are sizeable; not in the sense that they were fairly large or that the number of the components and their features are sizeable, but in the sense that you can make them fairly large on the screen if you like, or small or whatever size.

The Sizeable interface, shared by all components, provides a number of manipulation methods and constants for setting the height and width of a component in absolute or relative units, or for leaving the size undefined.

The size of a component can be set with setWidth() and setHeight() methods. The methods take the size as a floating-point value. You need to give the unit of the measure as the second parameter for the above methods. The available units are listed in Table 5.1, “Size Units” below.

mycomponent.setWidth(100, Sizeable.UNITS_PERCENTAGE);
mycomponent.setWidth(400, Sizeable.UNITS_PIXELS);

Alternatively, you can speficy the size as a string. The format of such a string must follow the HTML/CSS standards for specifying measures.

mycomponent.setWidth("100%");
mycomponent.setHeight("400px");

The "100%" percentage value makes the component take all available size in the particular direction (see the description of Sizeable.UNITS_PERCENTAGE in the table below). You can also use the shorthand method setSizeFull() to set the size to 100% in both directions.

The size can be undefined in either or both dimensions, which means that the component will take the minimum necessary space. Most components have undefined size by default, but some layouts have full size in horizontal direction. You can set the height or width as undefined with Sizeable.SIZE_UNDEFINED parameter for setWidth() and setHeight().

You always need to keep in mind that a layout with undefined size may not contain components with defined relative size, such as "full size". See Section 6.10.1, “Layout Size” for details.

The Table 5.1, “Size Units” lists the available units and their codes defined in the Sizeable interface.


If a component inside HorizontalLayout or VerticalLayout has full size in the namesake direction of the layout, the component will expand to take all available space not needed by the other components. See Section 6.10.1, “Layout Size” for details.

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