Vaadin7 Refcard
Vaadin7 Refcard
Download Vaadin Framework Read the Book of Vaadin Build an application for evaluation Vaadin 7 Fundamentals training
Get certied
vaadin.com/training
vaadin.com/certication
#85
Get More Refcardz! Visit refcardz.com
CONTENTS INCLUDE: Creating a Server-side UI Components Themes Class Diagram Data Binding Widget Integration... and more!
ABOUT VAADIN
Vaadin is a web application development framework that allows you to build web applications much as you would with traditional desktop frameworks, such as AWT or Swing. A UI is built hierarchically from user interface components contained in layout components. User interaction is handled in an event-driven manner. Vaadin supports both a server-side and a client-side development model. In the server-side model, the application code runs on a server, while the actual user interaction is handled by a client-side engine that runs in the browser. The client-server communications and client-side technologies, such as HTML and JavaScript, are invisible to the developer. The clientside engine runs as JavaScript in the browser, so there is no need to install plug-ins.
Browser
Client-Side Engine Built-in Widgets Add-on Widgets Custom Widgets
Web Browser
Client-Side Engine
HTTP AJAX Requests HTTP
Vaadin Service
n
Vaadin Servlet/Portlet
Vaadin Session
1 n
Web Page
Application Server
Java Web Application
Default Theme
extends
UI Logic
Back-End
UI
extends
UI Component
UI Events UI Changes
Data Binding
Application UI
Event Listener
Data Model
Application Theme
Back-End
Client-Side UI
Service
Figure 1: Vaadin Client-Server Architecture The client-side development model allows building new client-side widgets and user interfaces with the GWT toolkit included in Vaadin. The widgets can be integrated with server-side component counterparts to enable using them in server-side applications. You can also make pure client-side UIs, which can communicate with a back-end service.
Figure 2: Architecture for Vaadin Applications You can create a Vaadin application project easily with the Vaadin Plugin for Eclipse, with NetBeans, or with Maven.
CREATING A SERVER-SIDE UI
A server-side Vaadin application consists of one or more UI classes that extend the com.vaadin.UI class and implement the init() method.
@Title(My Vaadin UI) public class HelloWorld extends com.vaadin.UI { @Override protected void init(VaadinRequest request) { // Create the content root layout for the UI VerticalLayout content = new VerticalLayout(); setContent(content); // Display the greeting content.addComponent(new Label(Hello World!));
Hot Tip
You can get a reference to the UI object associated with the currently processed request from anywhere in the application logic with UI.getCurrent(). You can also access the current VaadinSession, VaadinService, and VaadinServlet objects in the same way.
Vaadin Charts
The best charting component for Vaadin with over 50 chart types.
Learn more
vaadin.com/charts
Live examples
demo.vaadin.com/charts
Normally, you need to: extend the UI class build an initial UI from components define event listeners to implement the UI logic
DZone, Inc.
www.dzone.com
Vaadin 7
Event Listeners
In the event-driven model, user interaction with user interface components triggers server-side events, which you can handle with event listeners. In the following example, we handle click events for a button with an anonymous class:
Button button = new Button(Click Me); button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { Notification.show(Thank You!); } }); layout.addComponent(button);
Field Properties
Field properties are defined in the Field interface and the AbstractField base class for fields.
Property
required requiredError
Description
Boolean value stating whether a value for the field is required. (Default: false) Error message to be displayed if the field is required but empty. Setting the error message is highly recommended for providing the user with information about a failure.
Value changes in a field component can be handled correspondingly with a ValueChangeListener. By setting the immediate property of a component to true, user interaction events can be fired immediately when the focus changes. Otherwise, they are delayed until the first immediate interaction, such as a button click. In addition to the event-driven model, UI changes can be made from the server-side with server push.
Sizing
The size of components can be set in fixed or relative units in either dimension (width or height), or be undefined to shrink to fit the content.
Method
setWidth() setHeight()
Description
Set the component size in either fixed units (px, pt, pc, cm, mm, in, em, or rem) or as a relative percentage (%) of the containing layout. The null value or -1 means undefined size (see below), causing the component to shrink to fit the content. Sets both dimensions to 100% relative size Sets both dimensions as undefined, causing the component to shrink to fit the content.
Deployment
Vaadin applications are deployed to a Java application server as web applications. A UI runs as a Java Servlet, which needs to be declared in a web.xml deployment descriptor, or with the @WebServlet and @VaadinServletConfiguration annotations in a Servlet 3.0 capable server as follows:
@WebServlet(value = /*, asyncSupported = true) @VaadinServletConfiguration( productionMode = false, ui = HelloWorld.class) public class myServlet extends VaadinServlet { }
setSizeFull() setSizeUndefined()
Figure 4 shows the default sizing of components. Notice that a layout with an undefined size must not contain a component with a relative (percentual) size.
Validation
The VaadinServlet handles server requests and manages user sessions and UIs. All that is normally hidden, but you may need to do some tasks in the custom servlet class. The Eclipse plugin creates the servlet class as an inner class of the UI class. In a Servlet 2.4 capable server, you need to use a web.xml. Vaadin UIs can also be deployed as portlets in a portal.
Field values can be validated with validate() or isValid(). You add validators to a field with addValidator(). Fields in a FieldGroup can all be validated at once. Built-in validators are defined in the com.vaadin.data.validator package and include:
Validator
CompositeValidator DateRangeValidator Double(Range)Validator EmailValidator Integer(Range)Validator NullValidator RegexpValidator StringLengthValidator
Description
Combines other validators The date/time is between a specified range The input is a double value (and within a range) The input is a valid email address The input is an integer (and within a range) The input value either is null or is not The input string matches a regular expression The length of the input string is within a range
COMPONENTS
Vaadin components include field, layout, and other components. The component classes and their inheritance hierarchy is illustrated in Figure 4.
Component Properties
Common component properties are defined in the Component interface and the AbstractComponent base class for all components.
Property
caption description enabled icon immediate
Description
A label usually shown above, left of, or inside a component, depending on the component and the containing layout. A longer description that is usually displayed as a tooltip when mouse hovers over the component. If false, the component is shown as grayed out and the user cannot interact with it. (Default: true) An icon for the component, usually shown left of the caption, specified as a resource reference. If true, value changes are communicated immediately to the server-side, usually when the selection changes or the field loses input focus. (Default: false) The current country and/or language for the component. Meaning and use is application-specific for most components. (Default: UI locale) If true, the user cannot change the value. (Default: false) Whether the component is actually visible or not. (Default: true) DZone, Inc.
|
You can also implement a custom Validator by defining its validate() method. Fields in a FieldGroup bound to a BeanItem can be validated with the Bean Validation API (JSR-303), if an implementation is included in the class path.
Resources
Icons, embedded images, hyperlinks, and downloadable files are referenced as resources.
Button button = new Button(Button with an icon); button.setIcon(new ThemeResource(img/myimage.png));
locale
External and theme resources are usually static resources. Connector resources are served by the Vaadin servlet.
readOnly visible
www.dzone.com
Vaadin 7
Resource
ConnectorResource
FileResource
Expand Ratios
ExternalResource
ClassResource
The ordered layouts and GridLayout support expand ratios that allow some components to take the remaining space left over from other components. The ratio is a float value and components have 0.0f default expand ratio. The expand ratio must be set after the component is added to the layout.
VerticalLayout layout = new VerticalLayout(); layout.setSizeFull(); layout.addComponent(new Label(Title)); // Doesnt expand TextArea area = new TextArea(Editor); area.setSizeFull(); layout.addComponent(area); layout.setExpandRatio(area, 1.0f);
ThemeResource
StreamResource
Class Name
ExternalResource ThemeResource
Description
Any URL A static resource served by the application server from the current theme. The path is relative to the theme folder. Loaded from the file system Loaded from the class path Provided dynamically by the application
Custom Layout
The CustomLayout component allows the use of a HTML template that contains location tags for components, such as <div location=hello/>. The components are inserted in the location elements with the addComponent() method as shown below:
CustomLayout layout = new CustomLayout(mylayout); layout.addComponent(new Button(Hello), hello);
LAYOUT COMPONENTS
The layout of a UI is built hierarchically from layout components, or more generally component containers, with the actual interaction components as the leaf nodes of the component tree. You start by creating a root layout and set it as the UI content with setContent(). Then you add the other components to that with addComponent(). Single-component containers, most notably Panel and Window, only hold a single content component, just as UI, which you must set with setContent(). The sizing of layout components is crucial. Their default sizes are marked in Figure 4, and can be changed with the sizing methods described earlier. Notice that if all the components in a layout have relative size in a particular direction, the layout may not have undefined size in that direction!
The layout name in the constructor refers to a corresponding .html file in the layouts subfolder in the theme folder, in the above example layouts/ mylayout.html. See Figure 5 for the location of the layout template file.
ADD-ON COMPONENTS
Hundreds of Vaadin add-on components are available from the Vaadin Directory, both free and commercial. You can download them as an installation package or retrieve with Maven, Ivy, or a compatible dependency manager. Please follow the instructions given in Vaadin Directory at http://vaadin.com/directory. Most add-ons include widgets, which need to be compiled to a project widget set. In an Eclipse project created with the Vaadin Plugin for Eclipse, select the project and click the Compile Vaadin widgets button in the tool bar.
Margins
Setting setMargin(true) enables all margins for a layout, and with a MarginInfo parameter you can enable each margin individually. The margin sizes can be adjusted with the padding property (as top, bottom, left, and right padding) in a CSS rule with a corresponding v-top-margin, v-bottommargin, v-left-margin, or v-right-margin selector. For example, if you have added a custom mymargins style to the layout:
.mymargins.v-margin-left .mymargins.v-margin-right .mymargins.v-margin-top .mymargins.v-margin-bottom {padding-left: {padding-right: {padding-top: {padding-bottom: 10px;} 20px;} 30px;} 40px;}
THEMES
Vaadin allows customizing the appearance of the user interface with themes. Themes can include Sass or CSS style sheets, custom layout HTML templates, and graphics.
Spacing
Setting setSpacing(true) enables spacing between the layout slots. The spacing can be adjusted with CSS as the width or height of elements with the v-spacing style. For example, for a vertical layout:
.v-vertical > .v-spacing {height: 50px;}
Custom themes are placed under the VAADIN/themes/ folder of the web application (under WebContent in Eclipse projects). This location is fixed and the VAADIN folder specifies that these are static resources specific to Vaadin. The structure is illustrated in Figure 5. Each theme has its own folder with the name of the theme. A theme folder must contain a styles.scss (for Sass) or a styles.css (for plain CSS) style sheet. Custom layouts must be placed in the layouts sub-folder, but other contents may be named freely. Custom themes need to inherit a base theme. The built-in themes in Vaadin 7 are reindeer, runo, and chameleon, as well as a base theme on which the other built-in themes are based.
For a GridLayout, you need to set the spacing as left/top padding for a .v-gridlayout-spacing-on element:
.v-gridlayout-spacing-on { padding-left: 100px; padding-top: 50px; }
Sass Themes
Alignment
When a layout cell is larger than a contained component, the component can be aligned within the cell with the setComponentAlignment() method as in the example below:
VerticalLayout layout = new VerticalLayout(); Button button = new Button(My Button); layout.addComponent(button); layout.setComponentAlignment(button, Alignment.MIDDLE_CENTER);
Sass (Syntactically Awesome StyleSheets) is a stylesheet language based on CSS3, with some additional features such as variables, nesting, mixins, and selector inheritance. Sass themes need to be compiled to CSS. Vaadin includes a Sass compiler that compiles stylesheets on-the-fly during development, and can also be used for building production packages. To enable multiple themes on the same page, all the style rules in a theme should be prefixed with a selector that matches the name of the theme. It is defined with a nested rule in Sass. Sass themes are usually organized in two files: a styles.scss and a theme-specific file such as mytheme.scss.
|
DZone, Inc.
www.dzone.com
Vaadin 7
Server-Side Components
Legend
java.package.path css-style method() java.package.path
Data Model
Viewer
Interface
Inner
java.package.path
Inherits or implements
Container n
com.vaadin.data addItem()
Editor
Class
Inner
AbstractClass
Inner
abstractMethod() (must or may implement) 100% wide/high fixed undefined width/height
Viewer Editor
Item
com.vaadin.data addItemProperty()
getBean()
BeanItem<>
AbstractBeanContainer<>
Default sizes:
ClickListener
n Property<>
setValue() getValue()
Label
v-label
Button
v-button
Connector
com.vaadin.shared
com.vaadin.data
Viewer Editor
Link
v-link
NativeButton
v-nativebutton
ClientConnector
focus() setTabIndex()
com.vaadin.server
Upload
v-upload
Sizeable
MenuBar
v-menubar
Component
setEnabled/Visible() getParent()/attach()
com.vaadin.ui
Focusable
Validatable
validate/isValid() addListener()
Item 1 Field<> n
FieldGroup
<String>
TextField
v-textfield
Buffered
setBuffered() commit() discard()
MenuItem addItem()
AbstractComponent
setDescription() setImmediate
AbstractField<>
AbstractTextField
setInputPrompt/MaxLength() <String> v-richtextarea setRows() <Boolean> v-checkbox <Double>
PasswordField
v-textfield
AbstractEmbedded
AbstractMedia
AbstractColorPicker
RichTextArea
TextArea
v-textarea setRows() <Double>
Image
v-image
Video
v-video
ColorPicker
v-colorpicker
Flash
v-flash
Audio
v-audio
ColorPickerArea
v-colorpicker
CheckBox
ProgressIndicator
v-progressindicator setIndeterminate() setPollingInterval()
Calendar
v-calendar
Slider
BrowserFrame
v-browserframe
Embedded
v-container
HasComponents
ComponentContainer
addComponent()
CustomComponent
v-customcomponent setCompositionRoot()
DateField
InlineDateField
v-inlinedatefield
setResolution()
SingleComponentContainer
AbstractComponentContainer
DragAndDropWrapper
v-ddwrapper <Object>
CustomField<>
v-customfield Container is 1wraps initContent()
PopupDateField
v-datefield
AbstractSingleComponentContainer
setContent()
UI
init()
TabSheet
v-tabsheet Tab addTab()
AbstractSelect
setMultiSelect()
ComboBox
v-filterselect
setContainerDataSource()
Panel
v-panel
Your UI Layout
Accordion
v-accordion
NativeSelect
v-nativeselect
TwinColSelect
v-twincolselect
Window
v-window UI.getCurrent().addWindow()
AbsoluteLayout
v-absolutelayout ComponentPosition getPosition()
ListSelect
v-listselect
CustomLayout
v-customlayout new CustomLayout("template")
AbstractLayout
CssLayout
v-csslayout
setMargin/Spacing() setVerticalExpandRatio() setHorizontalExpandRatio() setComponentAlignment()
Tree
v-tree
ItemStyleGenerator
Container.Hierarchical
AbstractSplitPanel
Horizontal-/ VerticalSplitPanel
setSplitPosition() setLocked()
GridLayout
Table
ColumnGenerator RowGenerator CellStyleGenerator
v-table
TreeTable
v-treetable Collapsible Container.Ordered Container.Sortable
v-splitpanel-horizontal/-vertical
AbstractOrderedLayout
setMargin/Spacing()
FormLayout
v-formlayout
setComponentAlignment/ExpandRatio()
HorizontalLayout
v-horizontallayout
VerticalLayout
v-verticallayout
The Class Diagram presents all user interface component classes and the most important interfaces, relationships, and methods.
www.dzone.com
Vaadin 7
For selection components, the property value points to the item identifier of the current selection, or a collection of item identifiers in the multiSelect mode. The ObjectProperty is a wrapper that allows binding any object to a component as a property.
- a custom theme
@import "mytheme.scss";
Items
An item is an ordered collection of properties. The Item interface also associates a property ID with each property. Common uses of items include form data, Table rows, and selection items. The BeanItem is a special adapter that allows accessing any Java bean (or POJO with proper setters and getters) through the Item interface. Forms can be built by binding fields to an item using the FieldGroup utility class.
- custom layouts
Figure 5: Theme Contents With this organization, the styles.scss would be as follows:
@import mytheme.scss; /* Enclose theme in a nested style with the theme name. */ .mytheme { @include mytheme; /* Use the mixin defined in mytheme.scss */ }
Containers
A container is a collection of items. It allows accessing the items by an item ID associated with each item. Common uses of containers include selection components, as defined in the AbstractSelect class, especially the Table and Tree components. (The current selection is indicated by the property of the field, which points to the item identifier of the selected item.) Vaadin includes the following built-in container implementations:
The mytheme.scss, which contains the actual theme rules, would define the theme as a Sass mixin as follows:
/* Import a base theme.*/ @import ../reindeer/reindeer.scss; @mixin mytheme { /* Include all the styles from the base theme */ @include reindeer; /* Insert your theme rules here */ .mycomponent { color: red; }
Container Class
IndexedContainer BeanItemContainer BeanContainer HierarchicalContainer FilesystemContainer SQLContainer JPAContainer
Description
Container with integer index keys Bean container that uses bean as item ID Bean container with explicit item ID type Tree-like container, used especially by the Tree and TreeTable components Direct access to the file system Binds to an SQL database Binds to a JPA implementation
Every component has a default CSS class based on the component type, and you can add custom CSS classes for UI components with addStyleName(), as shown below.
Applying a Theme
Also, all components that can be bound to containers are containers themselves.
Buffering
All field components implement the Buffered interface that allows buffering user input before it is written to the data source.
Method
commit() discard() setBuffered()
Description
Validates the field or field group and, if successful, writes the buffered data to the data source Discards the buffered data and re-reads the data from the data source Enables buffering when true. Default is false.
DATA BINDING
Vaadin allows binding components directly to data. The data model, illustrated in Figure 4, is based on interfaces on three levels of containment: properties, items, and containers.
The FieldGroup class has the same methods to manage buffering for all bound fields.
WIDGET INTEGRATION
The easiest way to create new components is composition with the CustomComponent. If that is not enough, you can create an entirely new component by creating a client-side GWT (or JavaScript) widget and a server-side component, and binding the two together with a connector, using a shared state and RPC calls.
Properties
The Property interface provides access to a value of a specific class with the setValue() and getValue() methods. All field components provide access to their value through the Property interface, and the ability to listen for value changes with a Property.ValueChangeListener. The field components hold their value in an internal data source by default, but you can bind them to any data source with setPropertyDataSource(). Conversion between the field type and the property type is handled with a Converter.
DZone, Inc.
www.dzone.com
Vaadin 7
Client-Side (GWT)
Widget
Connector
RPC
The client-side source files must normally be located in a client subpackage in the same package as the descriptor.
State
You can associate a stylesheet with a widget set with the <stylesheet> element in the .gwt.xml descriptor:
<stylesheet src=mycomponent/styles.css/>
Component
Server-Side
Figure 6: Integrating a Client-Side widget with a Server-Side API Shared state is used for communicating component state from the serverside component to the client-side connector, which should apply them to the widget. The shared state object is serialized by the framework. You can make RPC calls both from the client-side to the server-side, typically to communicate user interaction events, and vice versa. To do so, you need to implement an RPC interface.
Figure 7 illustrates the source code structure of a widget project, as created with the Vaadin Plugin for Eclipse.
com.example.mycomponent MyComponent.java MyComponentWidgetSet.gwt.xml client mycomponent MyComponentWidget.java MyComponentConnector.java MyComponentState.java MyComponentClientRpc.java MyComponentServerRpc.java public mycomponent styles.css
- client-side widget - integration connector - shared state - server-to-client RPC interface - client-to-server RPC interface - static content for widget set
A widget set is a collection of widgets that, together with inherited widget sets and the communication framework, forms the Client-Side Engine of Vaadin when compiled with the GWT Compiler into JavaScript. A widget set is defined in a .gwt.xml GWT Module Descriptor. You need to specify at least one inherited base widget set, typically the DefaultWidgetSet or other widget sets.
RECOMMENDED BOOK
READ NOW
http://vaadin.com/book
Free PDF
DZone, Inc. 150 Preston Executive Dr. Suite 201 Cary, NC 27513 DZone communities deliver over 6 million pages each month to more than 3.3 million software developers, architects and decision makers. DZone offers something for everyone, including news, tutorials, cheat sheets, blogs, feature articles, source code and more. "DZone is a developer's dream", says PC Magazine.
Copyright 2013 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
888.678.0399 919.678.0300 [email protected] Sponsorship Opportunities [email protected] $7.95 Refcardz Feedback Welcome
Version 1.0