Getting Started With Vaadin Framework 8
Getting Started With Vaadin Framework 8
85
CONTENTS
Framework 8
Components
Layout Components
Themes
Data Binding... and more!
BY MATTI TAHVONEN - ORIGINAL BY MARKO GRÖNROOS
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
Application UI logic
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.
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
Button NativeButton
CLASS DIAGRAM
AbstractEmbedded
AbstractFocusable
AbstractMedia Vaadin Framework
Label Upload
AbstractJavaScriptComponent BrowserFrame
Sizeable ComponentContainer
Embedded Composite
Layout
AbstractComponent
1
HasValue<T> HasItems<T> HasHierarchicalDataProvider<T> HasDataProvider<T>
NativeSelect<T> TwinColSelect<T>
TreeGrid<T>
ComboBox<T> ListSelect<T>
CheckBox Slider
asSingleSelect()
asMultiSelect()
ColorPickerGradient RichTextArea
AbstractDateField AbstractColorPicker
AbstractTextField
AbstractSingleComponentContainer AbstractComponentContainer
AbstractLocalDateTimeField TextArea
AbstractSplitPanel
HorizontalSplitPanel
PasswordField UI
DateField
AbstractLayout VerticalSplitPanel
LoginForm
InlineDateField
ColorPicker
Panel
ColorPickerArea
ColorPickerPopup Window
InlineDateTimeField AbsoluteLayout CustomLayout VerticalLayout
AbstractOrderedLayout FormLayout
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
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.
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:
@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.
are static resources specific to your Vaadin application. The ... Other theme resources, Sass files, images etc
Each theme has its own folder with the name of the theme. styles.scss Sass file that combines all relevant style rules
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.
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()));
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
Component
Server-Side
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
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.