Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4K views

Getting Started With Vaadin Framework 8

Vaadin Framework is a productive and easy-to-use UI library for developing web applications in Java or your JVM language of choice.

Uploaded by

Aissa Aouli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Getting Started With Vaadin Framework 8

Vaadin Framework is a productive and easy-to-use UI library for developing web applications in Java or your JVM language of choice.

Uploaded by

Aissa Aouli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

BROUGHT TO YOU IN PARTNERSHIP WITH

85
CONTENTS

Getting Started with Vaadin 



About Vaadin Framework
Bootstrapping a Project

Framework 8
 Components
 Layout Components
 Themes
 Data Binding... and more!
BY MATTI TAHVONEN - ORIGINAL BY MARKO GRÖNROOS

ABOUT VAADIN FRAMEWORK BOOTSTRAPPING A PROJECT

Vaadin Framework is a productive and easy-to-use UI library for You can create a Vaadin application project easily from Maven
developing web applications in Java or your JVM language of archetypes. To create a simple app stub, use the following
choice. Vaadin’s strong abstraction of web technologies gives command (or use the same groupId and archetypeId in your IDE):
you a component-based approach to build your apps, almost
mvn archetype:generate -DarchetypeGroupId=com.vaadin
like you’re building traditional desktop apps, but through -DarchetypeArtifactId=vaadin-archetype-application
state-of-the-art web technologies. You use an object-oriented -DarchetypeVersion=LATEST
approach to compose your UI from smaller UI components and
layouts, and hook your logic to the UI with event listeners. start.spring.io also provides an option to include Vaadin
dependencies to your Spring project. The most commonly used
In addition to providing high-level UI components, which IDEs (IntelliJ, Eclipse, and Netbeans) also have built in support
saves you from time-consuming HTML, CSS, and JavaScript or plugins that can help to create Vaadin applications.
programming, Vaadin also abstracts away the communication
between the server and the browser. This makes both the UI THE UI CLASS: THE ENTRY POINT TO YOUR APPLICATION
and backend development easier (no need to expose REST The UI class (extends the com.vaadin.UI) is the entry point
services) and increases security. to your application. The framework creates an instance when
the user opens the page in the browser and calls the init
Vaadin Framework is open source and licensed under the liberal method init().
Apache 2 license.
@Title(“My Vaadin UI”)
public class HelloWorld extends com.vaadin.UI {
@Override
Web Browser protected void init(VaadinRequest request) {
// Create the content root layout for the UI
Vaadin Client-Side Add-ons Theme VerticalLayout content = new VerticalLayout();
setContent(content);
// Display the greeting
HTTP AJAX Requests or WebSocket connection content.addComponent(new Label(“Hello World!”));
}
Application }
Vaadin Framework Server
Java Web
Application
UI components Data Binding

Automatic communication UI events

Application UI logic

Back-End (Business logic, persistence, database, ...) PRIME


Ensure your success with our support.
vaadin.com/pricing
Figure 1 Vaadin Client-Server Architecture

For extending the framework, there are numerous add-ons built


by Vaadin and the community. The Directory service currently
lists nearly 700 add-ons for Vaadin Framework.

DZONE.COM | © DZONE, INC. VISIT DZONE.COM/REFCARDZ FOR MORE!


BECOMING A VAADIN EXPERT

While Vaadin has the lowest learning curve Vaadin also offers exceptionally good
on the market, the web application documentation, tutorials and official
ecosystem keeps evolving continuously. hands-on trainings all around the world.

With our subscription based offerings you’ll Attend our official Vaadin trainings to learn
make sure to always benefit from the newest about Vaadin Best Practices, the right
technologies and stay ahead of the learning application architecture or how to best
curve. benefit from the latest features in browsers
or our tools.
Benefit from the easy integration of our
charts library or speed up your development We offer a broad selection of over 30 courses
with the visual designer and our various that will help you stay a web development
other tools. expert.

CORE PRO PRIME

Vaadin Framework All CORE features All CORE + PRO features

Access to 600+ add-ons Designer Expert Chat

Discussion forum TestBench Development on Demand

Extensive documentation Charts Warranty

Spreadsheet

Board

AVAI L ABLE F OR PR O AN D PR I ME

TRAINING SUBSCRIPTION
Unlimited access to expert lead trainings and
certifications online and live.

vaadin.com/pricing
3 GETTING STARTED WITH VAADIN

Normally, you need to: ValueChangeListener, and TabSheet allows you to listen to
• Extend the UI class. tab changes using SelectedTabChangeListener. Many field
• Build an initial UI from components components allow to track focus using FocusListener.
• Define event listeners to implement the UI logic.
In addition to the event-driven model, UI changes can be
Optionally, you can also: made from other places than UI initiated threads. Changes are
• Set a custom theme for the UI. reflected automatically if you have enabled server push (using
• Bind components to data. vaadin-push module and @Push annotation to UI class) or use
• Bind components to resources. polling configured to the UI class. The push mode primarily uses
WebSockets for communication and falls back to long polling if
Tip: You can get a reference to the UI object associated with the it’s not supported.
currently processed request from anywhere in the application
public void notifyUI(YourAppUI activeUI, String msg) {
logic with UI.getCurrent(). You can also access the current // ensure proper synchronization using
VaadinSession, VaadinService, and VaadinServlet objects in the // the UI.access method when called
// from a non-UI initiated event
same way.
activeUI.access(() -> {
activeUI.showMessageInUI(msg);
DEPLOYMENT // method in your UI class
To expose UI classes for end users, you’ll need a VaadinServlet });
}
deployed to a servlet container. The VaadinServlet handles server
requests and manages user sessions and UIs. If you use Vaadin
Spring or Vaadin CDI (available in the Vaadin Directory), the
COMPONENTS
servlet is configured automatically, and you only need to expose
Vaadin components include field, layout, and other components.
your UI class using @SpringUI or @CDIUI(“”) annotation. In
The component classes, related helper classes, and their
a basic servlet container project, like the one that is generated by
inheritance hierarchy is illustrated in Figure 2.
vaadin-archetype-application, the servlet can be declared as such:

COMPONENT PROPERTIES
@WebServlet(urlPatterns = “/*”, name = “MyUIServlet”, Common component properties are defined in the Component
asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, interface and the AbstractComponent base class for all
productionMode = false) components.
public static class MyUIServlet extends VaadinServlet {
}
PROPERTY DESCRIPTION
Most of the time you don’t need to work at the servlet level at A label usually shown above, left of, or
all, but you can add customization to the servlet if you want. Caption inside a component, depending on the
In Spring and CDI projects, you can just expose a customized component and the containing layout.
version of SpringVaadinServlet or VaadinCDIServlet and the
automatic default version is then ignored. A longer description that is usually
Description displayed as a tooltip when the mouse
Vaadin UIs can also be deployed as portlets in a portal. Refer to
hovers over the component.
vaadin.com/docs for Portlet deployment.
If false, the component is shown as
EVENTS LISTENERS Enabled grayed out and the user cannot interact
In the event-driven model, user interactions with user interface with it. (Default: true.)
components trigger server-side events, which you can handle
with event listeners. An icon for the component, usually
Icon shown left of the caption, specified as a
In the following example, we handle click events for a button resource reference.
with an anonymous class:
The current country and/or language
for the component. Meaning and
Button button = new Button(“Click Me”); Locale
button.addClickListener(event-> { use is application-specific for most
Notification.show(“Thank You!”);
components. (Default: UI locale.)
});
layout.addComponent(button);
Whether the component is visible or
Visible
Different components provide different listeners. For example, not. (Default: true.)
value changes in a field component can be handled with a

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


4 GETTING STARTED WITH VAADIN

Button NativeButton
CLASS DIAGRAM
AbstractEmbedded

AbstractFocusable
AbstractMedia Vaadin Framework
Label Upload

PopupView MenuBar Flash Audio ClientConnector Connector

ProgressBar Link Image Video


Component HasComponents

AbstractJavaScriptComponent BrowserFrame
Sizeable ComponentContainer
Embedded Composite

Layout
AbstractComponent

1
HasValue<T> HasItems<T> HasHierarchicalDataProvider<T> HasDataProvider<T>

AbstractField AbstractListing RadioButtonGroup<T> CheckBoxGroup<T>


Tree<T>

NativeSelect<T> TwinColSelect<T>
TreeGrid<T>

ComboBox<T> ListSelect<T>
CheckBox Slider
asSingleSelect()
asMultiSelect()
ColorPickerGradient RichTextArea

ColorPickerGrid CustomField Grid<T> AbstractSingleSelect<T> AbstractMultiSelect<T>

AbstractDateField AbstractColorPicker

AbstractTextField
AbstractSingleComponentContainer AbstractComponentContainer

AbstractLocalDateTimeField TextArea

AbstractLocalDateField TextField Your UI class TabSheet Accordion

AbstractSplitPanel
HorizontalSplitPanel
PasswordField UI
DateField
AbstractLayout VerticalSplitPanel
LoginForm
InlineDateField
ColorPicker
Panel

ColorPickerArea

DateTimeField GridLayout CssLayout HorizontalLayout

ColorPickerPopup Window
InlineDateTimeField AbsoluteLayout CustomLayout VerticalLayout

AbstractOrderedLayout FormLayout

Validator<T> Binder<T> BeanValidationBinder<T>

Converter<P, M> StringToBolleanConverter LocalDateToDateConverter


BeanValidator
*
DateToLongConverter StringToDateConverter
Binding<B, T>
AbstractValidator<T>
DateToSqlDateConverter LocalDateTimeToDateConverter
ValueProvider<S, T>
AbstractStringToNumberConverter

StringLengthValidator DeclarativeValueProvider<T>

RegexpValidator
EmailValidator
StringToDoubleConverter StringToIntegerConverter
RangeValidator
StringToBigDecimalConverter StringToLongConverter

StringToBigIntegerConverter StringToFloatConverter

IntegerValidator BigDecimalRangeValidator

LongRangeValidator FloatRangeValidator
Legend Class Interface
ShortRangeValidator BigIntegerRangeValidator
Implements
or inherits
DoubleRangeValidator DateRangeValidator Component Class AbstractClass
Has

ByteRangeValidator DateTimeRangeValidator Field(HasValue) Class Uses

Figure 2 Class diagram

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


5 GETTING STARTED WITH VAADIN

FIELD PROPERTIES RESOURCES


Field implementations often extend from AbstractField<T> and Icons, embedded images, hyperlinks, and downloadable files
contain the following commonly used properties. are referenced as resources.

PROPERTY DESCRIPTION Button button = new Button(“Button with an icon”);


button.setIcon(new ThemeResource(“img/myimage.png”));

The actual value of the field. The


type depends on the field and External and theme resources are usually static resources.
possible configuration. Value Connector resources are served by the Vaadin servlet.
value changes can be monitored using
ValueChangeListener, but often
values are bound automatically Resource ConnectorResource ClassResource
using com.vaadin.data.Binder.
ThemeResource FileResource

A Boolean controlling whether


ExternalResource StreamResource
the component should be marked
requiredIndicatorVisible
as required in the UI (most often FontIcon VaadinIcons
using red * character).
Figure 3 Resource Classes and Interfaces
If true, the user cannot change
readOnly
the value. (Default: false.) CLASS NAME DESCRIPTION

ExternalResource Any URL.


The tab index property is used
to specify the order in which the A static resource served by the
tabIndex
fields are focused when the user application server from the current
presses the Tab key. ThemeResource
theme. The path is relative to the
theme folder.

FileResource Loaded from the file system.


SIZING
The size of components can be set in fixed or relative units by ClassResource Loaded from the class path.
either dimension (width or height), or be undefined to shrink to
fit the content. Provided dynamically by the
StreamResource
application.
METHOD DESCRIPTION

Set the component size in either fixed Font icon sets, such as VaadinIcons,
units (px,pt, pc, cm, mm, in, em, or FontIcon contain a selection of special
rem) or as a relative percentage (%) resources that can be used as icons.
setWidth() of the available area provided by the
setHeight() containing layout. The null value or -1
means undefined size (see below), LAYOUT COMPONENTS
causing the component to shrink to fit
the content. The layout of a UI is built hierarchically from layout components,
or more generally component containers, with the actual
setSizeFull() Sets both dimensions to 100% relative size. interaction components as the leaf nodes of the component tree.

You start by creating a root layout and setting it as the UI


Sets both dimensions as undefined,
content with setContent(). Then you add the other components
setSizeUndefined() causing the component to shrink to its
to that with addComponent(). Single-component containers,
minimum size.
most notably Panel and Window, only hold a single content
component, just as UI, which you must set with setContent().
Notice that a layout with an undefined size must not contain a
component with a relative (percentual) size. For more tips on The sizing of layout components is crucial. You can either use
how to use relative sizes, refer to the Layout section. explicit size or define it relatively from the area provided by the

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


6 GETTING STARTED WITH VAADIN

parent component. Notice that if all the components in a layout


VerticalLayout layout = new VerticalLayout();
have relative size in a particular direction, the layout may not layout.setSizeFull();
have undefined size in that direction! layout.addComponent(new Label(“Title”));
// Doesn’t expand
Tip: Besides building your layouts in Java, you can also layout TextArea area = new TextArea(“Editor”);
your view in declarative HTML format or visually by using area.setSizeFull();
layout.addComponent(area);
Vaadin Designer inside Eclipse or IntelliJ. layout.setExpandRatio(area, 1.0f);

MARGINS
Certain layout components support setting margins VerticalLayout and HorizontalLayout also contain a helper
programmatically. Setting setMargin(true) enables all margins method called addComponentsAndExpand(Component…) that
for a layout, and with a MarginInfo parameter you can enable adds a component and adjusts expand ratios and component
each margin individually. The margin sizes can be adjusted with sizes that suit most common use cases. The above can be
the padding property (as top, bottom, left, and right padding) flattened to:
in a CSS rule with a corresponding v-top-margin, v-bottom-
VerticalLayout layout = new VerticalLayout();
margin, v-left-margin, or v-right-margin selector. For example, layout.addComponent(new Label(“Title”));
if you have added a custom mymargins style to the layout: // Doesn’t expand
TextArea area = new TextArea(“Editor”);
.mymargins.v-margin-left {padding-left: 10px;} layout.addComponentsAndExpand(area);
.mymargins.v-margin-right {padding-right: 20px;}
.mymargins.v-margin-top {padding-top: 30px;}
.mymargins.v-margin-bottom {padding-bottom: 40px;} The Grid component also supports expand ratios for columns.

CUSTOM LAYOUT
SPACING
The CustomLayout component allows the use of an HTML
Certain layout components also support the setSpacing(true)
template that contains location tags for components, such as
method that controls spacing between the layout slots. Spacing
<div location=”hello”/>. The components are inserted in the
can be adjusted with CSS as the width or height of the elements
location elements with the addComponent() method as
with the v-spacing style. For example, for a vertical layout:
shown below:
.v-vertical > .v-spacing {height: 50px;}
CustomLayout layout = new CustomLayout(
getClass().getResourceAsStream(“mylayout.html”));
For a GridLayout, you need to set the spacing as left/top layout.addComponent(new Button(“Hello”), “hello”);
padding for a .v-gridlayout-spacing-on element:
The layout content is given as an InputStream or it can also be a
.v-gridlayout-spacing-on {
padding-left: 100px; named resource file in your theme directory.
padding-top: 50px;
}
ADD-ON COMPONENTS
Your application might require less frequently needed features or
ALIGNMENT UI components, which are not included in the core distribution.
When an area provided by the layout component is larger than Hundreds of Vaadin add-on components are available in the
a contained component, the component can be aligned within Vaadin Directory, both free and commercial. To use a component,
the cell with the setComponentAlignment() method as in the just copy the dependency information for Maven or download
example below: the jar files from Directory into your project.
VerticalLayout layout = new VerticalLayout();
Button button = new Button(“My Button”); Many of the add-ons contain client side extensions. These add-
layout.addComponent(button); ons require you have a widgetset that combines both built in
layout.setComponentAlignment(button,
Alignment.MIDDLE_CENTER); and custom client side extensions into one compact client-side
engine. If you created your add-on with vaadin-archetype-
application, your application is ready for add-on usage out of
EXPANDING COMPONENTS TO AVAILABLE SPACE the box, but remember to execute “mvn clean install” (or the
The ordered layouts and GridLayout support expand ratios, same via your IDE) to ensure the client side engine is rebuilt.
to allow some components to take the remaining space left
over from other components. The ratio is a float value and If your project doesn’t have vaadin-maven-plugin (e.g. a start.
components have 0.0f default expand ratio. The expand ratio spring.io project or simplified example app), add the following
must be set after the component is added to the layout. build plugin to your project’s pom.xml file:

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


7 GETTING STARTED WITH VAADIN

<plugin> @import “mytheme.scss”;


<groupId>com.vaadin</groupId> @import “addons.scss”;
<artifactId>vaadin-maven-plugin</artifactId>
<version>${version.vaadin}</version> // This file prefixes all rules with the theme
<executions> // name to avoid causing conflicts with other themes.
<execution> // The actual styles should be defined in mytheme.scss
<goals>
<!-- Needed for theme: --> .mytheme {
<goal>update-widgetset</goal> @include addons;
<goal>compile</goal> @include mytheme;\
<!-- Needed for theme: --> }
<goal>update-theme</goal>
<goal>compile-theme</goal>
</goals> The mytheme.scss, which contains the actual theme rules,
</execution>
</executions>
would define the theme as a Sass mix-in as follows:
</plugin>
@import “../valo/valo.scss”;

@mixin mytheme {
THEMES @include valo;

Vaadin allows customization of the appearance of the user // Insert your own theme rules here
.mycomponent { color: red; }
interface with themes. Themes can include Sass or CSS style
}
sheets, custom layout HTML templates, and graphics.

BASIC THEME STRUCTURE VAADIN/themes VAADIN/themes

Custom themes are placed under the /VAADIN/themes/ folder


valo default theme, in vaadin-themes.jar or as extracted
of the web application (src/main/webapp in Maven projects).
This location is fixed and the VAADIN folder specifies that these valo.scss main Sass theme file

are static resources specific to your Vaadin application. The ... Other theme resources, Sass files, images etc

structure is illustrated in Figure 4.


myapptheme VAADIN/themes
@import

Each theme has its own folder with the name of the theme. styles.scss Sass file that combines all relevant style rules

A theme folder must contain a styles.scss (for Sass) or a styles.


addons.scss automatically updated file that contains add-on styles
css (for plain CSS) style sheet. Custom layouts must be
placed in the layout’s sub-folder, but other contents may be mytheme.scss main Sass theme file, properties and custom rules

named freely. …. Other theme resources, Sass files, images etc

Custom themes need to inherit a base theme. The suggested Figure 4 Theme Contents
base theme is Valo, which is easily customizable using Sass
APPLYING A THEME
variables. Such a theme is created for you automatically if you
bootstrap your project is built on top of the vaadin-archetype- Every component has a default CSS class based on the
application archetype. component type, and you can add custom CSS classes for UI
components with addStyleName(), as shown below.

SASS THEMES You set the theme for a UI with the @Theme annotation.
Sass (Syntactically Awesome StyleSheets) is a stylesheet
language based on CSS3, with some additional features such @Theme(“mytheme”)
public class MyUI extends UI {
as variables, nesting, mixins, and selector inheritance. Sass
themes need to be compiled to CSS. Vaadin includes a Sass @Override
compiler that compiles stylesheets during the build process. protected void init(VaadinRequest vaadinRequest) {
//...
You can also use on-the-fly compilation during development, by Label label = new Label(“This is my themed
disabling the compilation from the build script. component”);
label.addStyleName(“mycomponent”);
layout.addComponent(label);
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 DATA BINDING
theme-specific file such as mytheme.scss.
Vaadin allows binding your Java domain classes directly to
With this organization, the styles.scss would be as follows: components. This way, you avoid writing a lot of boilerplate code.

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


8 GETTING STARTED WITH VAADIN

LISTING DATA IN GRID toString method. Selecting a String from a list of strings could
Grid, the component that shows your data in a tabular format, be accomplished as follows:
often plays a central part in a business application. The easiest
way to use Grid is to pass the data as a list, stream or an array. ComboBox<String> comboBox = new ComboBox<>();
In the following code example, Person is your domain object comboBox.setItems(“Foo”,”Bar”,”Car”);
(Java Bean): comboBox.addValueChangeListener(e ->
Notification.show(e.getValue()));

Grid<Person> grid = new Grid<>(Person.class);


grid.setItems(listOfPersons);
// define columns and the order as bean properties
If toString presentation doesn’t fit to your use case, you can in
// (default: show all) most select components customize the caption as follows:
grid.setColumns(“firstName”, “lastName”, “email”);

ComboBox<Person> cb = new ComboBox<>();


Alternatively, you can define columns programmatically. In this
cb.setItemCaptionGenerator(p -> p.getFirstName() +
case, you don’t need to pass the domain type as a constructor “ “ + p.getLastName());
parameter:
A similar concept is available for icons.
Grid<Person> grid = new Grid<>();
grid.setItems(listOfPersons);
grid.addColumn(Person::getFirstName)
BINDER FOR HANDY FORMS
.setCaption(“First name”); Binder is a helper class that allows you to bind a single
// ...
Java object’s properties to be displayed in multiple Vaadin
components. The most typical use case is a form. Binder also
The addColumn method returns a Column object that can supports two-way binding, so that values input by the end user
be used to further configure the column and the data automatically get written back to your domain model.
representation. In the above example, we only configure the
Binder will also help you to do value conversion and validation
caption of the column. With bean based listing your can get a
for the data. The following binds firstName(String) and age
reference to the Column with getColumn(“propertyName”).
(Integer) to two text fields.

LAZY LOADING DATA IN GRID


The setItems method stores the given data in your server Binder<Person> b = new Binder<>();
b.forField(firstNameField)
memory for rapid access. If your data grid contains a lot of data // additional configuration
and you wish to save some server memory, you can also do a .asRequired(“First name must be defined”)
lazy binding with your backend using setDataProvider method: .bind(Person::getFirstName, Person::setFirstName);
b.forField(ageField)
.withConverter(new StringToIntegerConverter(
grid.setDataProvider( “Must be valid integer!”))
(sortOrders, offset, limit) -> .withValidator(integer -> integer > 0,
service.findAll(offset, limit).stream(),
“Age must be positive”)
() -> service.count()
.bind(p -> p.getAge(), (p, i) -> p.setAge(i));
);
b.setBean(person);

The example above uses the easiest solution, in which you


Alternatively, you can make an automatic binding to your UI
only provide two lambda expressions: the first to provide the
classes member fields. The binding is made based on naming
given range of items and the second one that provides the total
convention, but it can be overridden with @PropertyId annotation.
number of items available. Alternatively, you can provide a
custom implementation of the DataProvider interface.
private TextField age = new TextField();
private TextField firstName = new TextField();
SELECTION COMPONENTS
Selection components (ComboBox, RadioButtonGroup, private void bindFields(Person person) {
ListSelect...) let your users pick one or several selections from Binder<Person> b = new Binder<>(Person.class);
// additional configuration supported
a set of given items. Grid is also a selection component. You
// also in name based binding
can use it as a single or multi-selection component using b.forMemberField(age).withConverter(
asSingleSelect() or asMultiSelect() method. new StringToIntegerConverter(“Must be integer”));
// this binds all found fields
To set the available items, you use the same setItems b.bindInstanceFields(this);
b.setBean(person);
or setDataProvider methods, as with Grid. Most select
}
components by default render the selections using item’s

DZONE.COM | © DZONE, INC. BROUGHT TO YOU IN PARTNERSHIP WITH


9 GETTING STARTED WITH VAADIN

Converters and Validators are often written by developers, but Shared state is used for communicating component state from
there is also a selection of built-in helper classes available. See the server-side component to the client-side connector, which
Figure 2 to see the built-in helpers. should apply them to the widget. The shared state object is
serialized by the framework.
WIDGET INTEGRATION
You can make RPC calls both from the client-side to the server-
The easiest way to create new components is composition side, typically to communicate user interaction events, and vice
with the CustomComponent or by extending from some layout versa. To do so, you need to implement an RPC interface.
component. If that is not enough, you can create an entirely
new component by creating a client-side widget (in GWT or CREATING A WIDGET PROJECT
JavaScript), a server-side counterpart, and binding the two You can create widgets directly to your application project, but
together with a connector, using a shared state and RPC calls. a much better habit is to create a separate add-on project for
your custom widgets and then add dependencies to it from
your application projects. Then you can build better tests that
Client-Side (GWT, JavaScript, WebComponent) are prepared for reuse in your other Vaadin projects or even
sharing your add-ons with others via the Directory service.
Widget

For widgets, there is a specially tailored project template:


RPC vaadin-archetype-widget. Create a project using that archetype
Connector
and follow its instructions in its README file. The archetype
also creates stubs for required classes.
RCP State

Component

Server-Side

Figure 5: Integrating a Client-Side widget with a Server-Side API

A B O U T T H E AU T H O R
MATTI TAHVONEN has a long history in Vaadin R&D: developing the core framework from the dark ages of
pure JS client side to the GWT era and creating number of official and unofficial Vaadin add-ons. His current
responsibility is to keep you up to date with latest and greatest Vaadin related technologies. When not
hacking with Java related technologies, he is most likely in the local bushes, coaching orienteers or driving
MTB, or sailing in the Baltic Sea. You can follow him on Twitter – @MattiTahvonen

BROUGHT TO YOU IN PARTNERSHIP WITH

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, research guides, feature articles,
source code and more.
DZONE, INC. REFCARDZ FEEDBACK
150 PRESTON EXECUTIVE DR. WELCOME
"DZone is a developer's dream," says PC Magazine. refcardz@dzone.com
CARY, NC 27513
SPONSORSHIP
Copyright © 2017 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval
888.678.0399 OPPORTUNITIES
system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
919.678.0300 sales@dzone.com
written permission of the publisher.

You might also like