640
Livro de Vaadin Vaadin 7ª Edição - 3ª Revisão

Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Embed Size (px)

DESCRIPTION

Book of-vaadin-br Book of-vaadin-br

Citation preview

Page 1: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Livro de VaadinVaadin 7ª Edição - 3ª Revisão

Page 2: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Livro de Vaadin: Vaadin 7ª Edição - 3ª RevisãoVaadin LtdMarko Grönroos

Vaadin 7ª Edição - 3ª Revisão EdiçãoFramework Vaadin 7.2.0

Published: 2014-11-03Copyright © 2000-2014 Vaadin Ltd

Resumo

Vaadin é um framework de desenvolvimento de aplicações web AJAX que permite aos desenvolvedorescriar interfaces de usuário de alta qualidade com Java, tanto no lado servidor quanto no cliente. Ele forneceum conjunto de bibliotecas de componentes de interface de usuário prontas para uso, e um framework paracriar seus próprios componentes. O foco é a facilidade de uso, reutilização, extensibilidade, e atender àsexigências de aplicações de grandes empresas.Todos os direitos reservados. Esta obra está licenciada sob a Creative Commons Licença CC-BY-ND Versão 2.0.

Page 3: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

ÍndicePrefácio .......................................................................................................................... xv

Part I. Introdução ............................................................................................................. 21

Chapter 1. Introdução ............................................................................................ 231.1. Visão Geral .............................................................................................. 231.2. Exemplo de Aplicação Passo a Passo ........................................................ 251.3. Suporte à IDE Eclipse ............................................................................... 261.4. Metas e Filosofia ...................................................................................... 271.5. Conhecimento .......................................................................................... 27

Chapter 2. Começando com Vaadin ....................................................................... 312.1. Visão Geral .............................................................................................. 312.2. Configurando o Ambiente de Desenvolvimento ........................................... 32

2.2.1. Instalando o SDK Java ................................................................... 332.2.2. Instalando o IDE Eclipse ................................................................. 342.2.3. Instalando o Apache Tomcat ........................................................... 352.2.4. Firefox e Firebug ............................................................................ 35

2.3. Visão Geral das Bibliotecas Vaadin ............................................................ 362.4. Instalando o Plugin Vaadin para Eclipse ..................................................... 37

2.4.1. Instalando o Plugin IvyDE ............................................................... 382.4.2. Instalando o Plugin Vaadin .............................................................. 392.4.3. Atualizando os Plugins ................................................................... 402.4.4. Atualizando as bibliotecas Vaadin .................................................... 41

2.5. Criando e Executando um Projeto com Eclipse ........................................... 412.5.1. Criando o Projeto ........................................................................... 412.5.2. Explorando o Projeto ...................................................................... 452.5.3. Dicas de Codificação para Eclipse .................................................. 472.5.4. Configurando e Iniciando o Servidor Web ........................................ 482.5.5. Executando e Depurando ............................................................... 49

2.6. Usando Vaadin com Maven ....................................................................... 502.6.1. Trabalhando a partir de Linha de Comando ...................................... 502.6.2. Compilando e Executando a Aplicação ............................................ 512.6.3. Utilizando Add-ons e Widget Sets customizados .............................. 52

2.7. Criando um projeto no IDE NetBeans ......................................................... 522.7.1. Projeto Maven a partir de um Archetype Vaadin ............................... 52

2.8. Criando um projeto com IntelliJ IDEA ......................................................... 532.8.1. Configurando um Servidor de Aplicações ........................................ 532.8.2. Criando um Projeto de Aplicação Vaadin Web .................................. 542.8.3. Criando um Projeto Maven ............................................................. 58

2.9. Pacote de instalação Vaadin ...................................................................... 622.9.1. Conteúdo do Pacote ....................................................................... 622.9.2. Instalação de Bibliotecas ................................................................ 63

2.10. Usando Vaadin com Scala ....................................................................... 63

Chapter 3. Arquitetura ........................................................................................... 653.1. Visão Geral .............................................................................................. 653.2. Conhecimento Tecnológico ........................................................................ 68

3.2.1. HTML e JavaScript ......................................................................... 683.2.2. Customizando com CSS e Sass ..................................................... 683.2.3. AJAX ............................................................................................. 693.2.4. Google Web Toolkit ........................................................................ 693.2.5. Servlets Java ................................................................................. 70

iBook of Vaadin

Page 4: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

3.3. Engine de Lado Cliente ............................................................................. 703.4. Eventos e Ouvintes ................................................................................... 71

Part II. Server-Side Framework ........................................................................................ 75

Chapter 4. Escrevendo uma Aplicação Web de Lado Servidor .............................. 774.1. Visão Geral .............................................................................................. 774.2. Construindo a UI ....................................................................................... 80

4.2.1. Arquitetura da Aplicação ................................................................. 814.2.2. Compondo Componentes ............................................................... 824.2.3. Navegação de View ........................................................................ 834.2.4. Acessando UI, Page, Session, e Service ......................................... 83

4.3. Manipulando Eventos com Ouvintes .......................................................... 844.3.1. Implementando um Ouvinte em uma Classe Regular ....................... 844.3.2. Diferenciando Fontes de Eventos .................................................... 844.3.3. A maneira Mais Fácil: Usando Classes Anônimas ........................... 85

4.4. Imagens e Outros Recursos ...................................................................... 864.4.1. Interfaces e Classes de Recursos ................................................... 864.4.2. Recursos de Arquivos .................................................................... 864.4.3. Recursos de Carregamento de Classe ............................................ 874.4.4. Recursos de Tema ......................................................................... 874.4.5. Recursos de Stream ...................................................................... 88

4.5. Manipulando Erros .................................................................................... 894.5.1. Indicador e Mensagem de Erro ....................................................... 894.5.2. Customizando Mensagens do Sistema ............................................ 904.5.3. Manipulando Exceções Não Tratadas ............................................. 91

4.6. Notificações .............................................................................................. 924.6.1. Tipos de Notificação ....................................................................... 934.6.2. Customizando Notificações ............................................................ 944.6.3. Customizando com CSS ................................................................. 94

4.7. Ciclo de Vida da Aplicação ........................................................................ 954.7.1. Implantação ................................................................................... 954.7.2. Servlet Vaadin, Portlet, e Serviço .................................................... 964.7.3. Sessão de Usuário ......................................................................... 974.7.4. Carregando uma UI ........................................................................ 984.7.5. Expiração de UI ............................................................................. 994.7.6. Expiração de Sessão ..................................................................... 994.7.7. Fechando uma Sessão ................................................................... 99

4.8. Implantando uma Aplicação ..................................................................... 1004.8.1. Criando um WAR Implantável no Eclipse ....................................... 1004.8.2. Conteúdo de Aplicações Web ....................................................... 1004.8.3. Classe de Servlet Web ................................................................. 1014.8.4. Usando um Descritor de Implantação web.xml ............................. 1014.8.5. Mapeamento de Servlets com Padrões de URL ............................. 1034.8.6. Outros Parâmetros de Configuração de Servlet .............................. 1044.8.7. Configuração de Implantação ........................................................ 106

Chapter 5. User Interface Components ............................................................... 1095.1. Overview ................................................................................................ 1105.2. Interfaces and Abstractions ...................................................................... 111

5.2.1. Component Interface ................................................................... 1125.2.2. AbstractComponent ................................................................... 113

5.3. Common Component Features ................................................................ 1135.3.1. Caption ........................................................................................ 1135.3.2. Description and Tooltips ................................................................ 114

ii

Livro de Vaadin

Page 5: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.3.3. Enabled ....................................................................................... 1155.3.4. Icon ............................................................................................. 1165.3.5. Locale ......................................................................................... 1175.3.6. Read-Only ................................................................................... 1205.3.7. Style Name .................................................................................. 1215.3.8. Visible ......................................................................................... 1215.3.9. Sizing Components ...................................................................... 1225.3.10. Managing Input Focus ................................................................ 123

5.4. Field Components ................................................................................... 1245.4.1. Field Interface ............................................................................. 1245.4.2. Data Binding and Conversions ...................................................... 1265.4.3. Handling Field Value Changes ...................................................... 1275.4.4. Field Buffering .............................................................................. 1275.4.5. Field Validation ............................................................................. 127

5.5. Component Extensions ........................................................................... 1305.6. Label ..................................................................................................... 130

5.6.1. Content Mode .............................................................................. 1315.6.2. Spacing with a Label .................................................................... 1325.6.3. CSS Style Rules .......................................................................... 133

5.7. Link ....................................................................................................... 1335.8. TextField ............................................................................................... 135

5.8.1. Data Binding ................................................................................ 1365.8.2. String Length ............................................................................... 1375.8.3. Handling Null Values .................................................................... 1375.8.4. Text Change Events ...................................................................... 1385.8.5. CSS Style Rules .......................................................................... 139

5.9. TextArea ................................................................................................ 1405.10. PasswordField ..................................................................................... 1415.11. RichTextArea ....................................................................................... 1415.12. Date and Time Input with DateField ....................................................... 143

5.12.1. PopupDateField ........................................................................ 1445.12.2. InlineDateField ......................................................................... 1475.12.3. Time Resolution ......................................................................... 1485.12.4. DateField Locale ........................................................................ 148

5.13. Button ................................................................................................. 1485.14. CheckBox ............................................................................................ 1495.15. Selection Components .......................................................................... 150

5.15.1. Binding Selection Components to Data ........................................ 1515.15.2. ComboBox ............................................................................... 1545.15.3. ListSelect ................................................................................. 1565.15.4. Native Selection Component NativeSelect .................................. 1575.15.5. Radio Button and Check Box Groups with OptionGroup .............. 1585.15.6. Twin Column Selection with TwinColSelect ................................. 1605.15.7. Allowing Adding New Items ......................................................... 1615.15.8. Multiple Selection ....................................................................... 1625.15.9. Other Common Features ............................................................ 163

5.16. Table .................................................................................................... 1635.16.1. Selecting Items in a Table ........................................................... 1655.16.2. Table Features ........................................................................... 1665.16.3. Editing the Values in a Table ........................................................ 1705.16.4. Column Headers and Footers ...................................................... 1735.16.5. Generated Table Columns ........................................................... 1755.16.6. Formatting Table Columns ........................................................... 1785.16.7. CSS Style Rules ......................................................................... 179

iii

Livro de Vaadin

Page 6: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.17. Tree ..................................................................................................... 1825.18. MenuBar .............................................................................................. 1835.19. Embedded Resources ........................................................................... 186

5.19.1. Embedded Image ...................................................................... 1875.19.2. Adobe Flash Graphics ................................................................ 1885.19.3. BrowserFrame .......................................................................... 1885.19.4. Generic Embedded Objects ....................................................... 188

5.20. Upload ................................................................................................. 1895.21. ProgressBar ........................................................................................ 1915.22. Slider ................................................................................................... 1945.23. Calendar .............................................................................................. 196

5.23.1. Date Range and View Mode ........................................................ 1975.23.2. Calendar Events ......................................................................... 1975.23.3. Getting Events from a Container .................................................. 1995.23.4. Implementing an Event Provider .................................................. 2015.23.5. Styling a Calendar ...................................................................... 2045.23.6. Visible Hours and Days ............................................................... 2055.23.7. Drag and Drop ........................................................................... 2055.23.8. Using the Context Menu .............................................................. 2075.23.9. Localization and Formatting ........................................................ 2075.23.10. Customizing the Calendar ......................................................... 2085.23.11. Backward and Forward Navigation ............................................. 2095.23.12. Date Click Handling .................................................................. 2095.23.13. Handling Week Clicks ............................................................... 2105.23.14. Handling Event Clicks ............................................................... 2105.23.15. Event Dragging ........................................................................ 2105.23.16. Handling Drag Selection ........................................................... 2125.23.17. Resizing Events ........................................................................ 213

5.24. Component Composition with CustomComponent ................................. 2135.25. Composite Fields with CustomField ...................................................... 214

Chapter 6. Managing Layout ................................................................................ 2156.1. Overview ................................................................................................ 2166.2. UI, Window, and Panel Content ................................................................ 2186.3. VerticalLayout and HorizontalLayout ..................................................... 218

6.3.1. Spacing in Ordered Layouts .......................................................... 2196.3.2. Sizing Contained Components ...................................................... 220

6.4. GridLayout ............................................................................................ 2236.4.1. Sizing Grid Cells .......................................................................... 225

6.5. FormLayout ........................................................................................... 2276.6. Panel ..................................................................................................... 229

6.6.1. Scrolling the Panel Content ........................................................... 2296.7. Sub-Windows ......................................................................................... 231

6.7.1. Opening and Closing Sub-Windows .............................................. 2316.7.2. Window Positioning ...................................................................... 2336.7.3. Scrolling Sub-Window Content ...................................................... 2336.7.4. Modal Sub-Windows ..................................................................... 233

6.8. HorizontalSplitPanel and VerticalSplitPanel .......................................... 2346.9. TabSheet ............................................................................................... 236

6.9.1. Adding Tabs ................................................................................. 2376.9.2. Tab Objects .................................................................................. 2376.9.3. Tab Change Events ...................................................................... 2386.9.4. Enabling and Handling Closing Tabs .............................................. 239

6.10. Accordion ............................................................................................ 240

iv

Livro de Vaadin

Page 7: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.11. AbsoluteLayout ................................................................................... 2416.12. CssLayout ........................................................................................... 244

6.12.1. CSS Injection ............................................................................. 2446.12.2. Browser Compatibility ................................................................. 245

6.13. Layout Formatting ................................................................................. 2466.13.1. Layout Size ................................................................................ 2466.13.2. Expanding Components .............................................................. 2476.13.3. Layout Cell Alignment ................................................................. 2486.13.4. Layout Cell Spacing .................................................................... 2506.13.5. Layout Margins ........................................................................... 251

6.14. Custom Layouts .................................................................................... 251

Chapter 7. Visual User Interface Design with Eclipse .......................................... 2557.1. Overview ................................................................................................ 2557.2. Creating a New Composite ...................................................................... 2577.3. Using The Visual Editor ........................................................................... 259

7.3.1. Adding New Components ............................................................. 2597.3.2. Setting Component Properties ...................................................... 2607.3.3. Editing an AbsoluteLayout .......................................................... 263

7.4. Structure of a Visually Editable Component .............................................. 2647.4.1. Sub-Component References ......................................................... 2657.4.2. Sub-Component Builders .............................................................. 2657.4.3. The Constructor ........................................................................... 266

Chapter 8. Themes ............................................................................................... 2678.1. Overview ................................................................................................ 2678.2. Introduction to Cascading Style Sheets .................................................... 269

8.2.1. Applying CSS to HTML ................................................................. 2698.2.2. Basic CSS Rules .......................................................................... 2698.2.3. Matching by Element Class ........................................................... 2708.2.4. Matching by Descendant Relationship ........................................... 2728.2.5. Importance of Cascading .............................................................. 2728.2.6. Style Class Hierarchy of a Vaadin UI .............................................. 2738.2.7. Notes on Compatibility .................................................................. 276

8.3. Syntactically Awesome Stylesheets (Sass) ............................................... 2768.3.1. Sass Overview ............................................................................. 2778.3.2. Sass Basics with Vaadin ............................................................... 2788.3.3. Compiling Sass Themes ............................................................... 278

8.4. Creating and Using Themes .................................................................... 2818.4.1. Sass Themes ............................................................................... 2818.4.2. Plain Old CSS Themes ................................................................. 2838.4.3. Styling Standard Components ....................................................... 2838.4.4. Built-in Themes ............................................................................ 2838.4.5. Add-on Themes ........................................................................... 285

8.5. Creating a Theme in Eclipse .................................................................... 2858.6. Valo Theme ............................................................................................ 286

8.6.1. Basic Use .................................................................................... 2878.6.2. Common Settings ......................................................................... 2878.6.3. Valo Fonts .................................................................................... 2898.6.4. Component Styles ........................................................................ 2908.6.5. Theme Optimization ..................................................................... 290

8.7. Custom Fonts ......................................................................................... 2918.7.1. Loading Fonts .............................................................................. 2918.7.2. Using Custom Fonts ..................................................................... 291

v

Livro de Vaadin

Page 8: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

8.8. Responsive Themes ................................................................................ 291

Chapter 9. Binding Components to Data ............................................................. 2979.1. Overview ................................................................................................ 2979.2. Properties .............................................................................................. 299

9.2.1. Property Viewers and Editors ........................................................ 3009.2.2. ObjectProperty Implementation ................................................... 3019.2.3. Converting Between Property Type and Representation .................. 3019.2.4. Implementing the Property Interface ............................................. 304

9.3. Holding properties in Items ...................................................................... 3059.3.1. The PropertysetItem Implementation ........................................... 3059.3.2. Wrapping a Bean in a BeanItem ................................................... 306

9.4. Creating Forms by Binding Fields to Items ................................................ 3089.4.1. Simple Binding ............................................................................. 3089.4.2. Using a FieldFactory to Build and Bind Fields ........................... 3089.4.3. Binding Member Fields ................................................................. 3099.4.4. Buffering Forms ........................................................................... 3109.4.5. Binding Fields to a Bean ............................................................... 3119.4.6. Bean Validation ............................................................................ 311

9.5. Collecting Items in Containers .................................................................. 3139.5.1. Basic Use of Containers ............................................................... 3139.5.2. Container Subinterfaces ............................................................... 3159.5.3. IndexedContainer ....................................................................... 3159.5.4. BeanContainer ........................................................................... 3169.5.5. BeanItemContainer .................................................................... 3199.5.6. Iterating Over a Container ............................................................. 3199.5.7. Filterable Containers ................................................................... 320

Chapter 10. Vaadin SQLContainer ....................................................................... 32310.1. Architecture .......................................................................................... 32410.2. Getting Started with SQLContainer ........................................................ 324

10.2.1. Creating a connection pool .......................................................... 32510.2.2. Creating the TableQuery Query Delegate .................................... 32510.2.3. Creating the Container ................................................................ 325

10.3. Filtering and Sorting .............................................................................. 32510.3.1. Filtering ..................................................................................... 32610.3.2. Sorting ...................................................................................... 326

10.4. Editing .................................................................................................. 32610.4.1. Adding items .............................................................................. 32610.4.2. Fetching generated row keys ....................................................... 32710.4.3. Version column requirement ........................................................ 32710.4.4. Auto-commit mode ..................................................................... 32710.4.5. Modified state ............................................................................ 328

10.5. Caching, Paging and Refreshing ............................................................ 32810.5.1. Container Size ........................................................................... 32810.5.2. Page Length and Cache Size ...................................................... 32810.5.3. Refreshing the Container ............................................................ 32910.5.4. Cache Flush Notification Mechanism ........................................... 329

10.6. Referencing Another SQLContainer ...................................................... 33010.7. Using FreeformQuery and FreeformStatementDelegate ....................... 33110.8. Non-implemented methods of Vaadin container interfaces ....................... 33210.9. Known Issues and Limitations ................................................................ 332

Chapter 11. Advanced Web Application Topics .................................................... 33511.1. Handling Browser Windows ................................................................... 336

vi

Livro de Vaadin

Page 9: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

11.1.1. Opening Popup Windows ............................................................ 33611.2. Embedding UIs in Web Pages ................................................................ 338

11.2.1. Embedding Inside a div Element ................................................ 33811.2.2. Embedding Inside an iframe Element ........................................ 34411.2.3. Cross-Site Embedding with the Vaadin XS Add-on ....................... 345

11.3. Debug Mode and Window ...................................................................... 34611.3.1. Enabling the Debug Mode ........................................................... 34611.3.2. Opening the Debug Window ........................................................ 34711.3.3. Debug Message Log .................................................................. 34711.3.4. General Information .................................................................... 34811.3.5. Inspecting Component Hierarchy ................................................. 34811.3.6. Communication Log .................................................................... 35011.3.7. Debug Modes ............................................................................ 351

11.4. Request Handlers ................................................................................. 35111.5. Shortcut Keys ....................................................................................... 352

11.5.1. Shortcut Keys for Default Buttons ................................................ 35211.5.2. Field Focus Shortcuts ................................................................. 35211.5.3. Generic Shortcut Actions ............................................................ 35311.5.4. Supported Key Codes and Modifier Keys ..................................... 355

11.6. Printing ................................................................................................. 35611.6.1. Printing the Browser Window ....................................................... 35611.6.2. Opening a Print Window ............................................................. 35611.6.3. Printing PDF .............................................................................. 357

11.7. Google App Engine Integration .............................................................. 35811.8. Common Security Issues ....................................................................... 359

11.8.1. Sanitizing User Input to Prevent Cross-Site Scripting .................... 35911.9. Navigating in an Application ................................................................... 360

11.9.1. Setting Up for Navigation ............................................................ 36011.9.2. Implementing a View .................................................................. 36111.9.3. Handling URI Fragment Path ....................................................... 361

11.10. Advanced Application Architectures ...................................................... 36411.10.1. Layered Architectures ............................................................... 36411.10.2. Model-View-Presenter Pattern ................................................... 365

11.11. Managing URI Fragments .................................................................... 36911.11.1. Setting the URI Fragment .......................................................... 36911.11.2. Reading the URI Fragment ........................................................ 36911.11.3. Listening for URI Fragment Changes ......................................... 37011.11.4. Supporting Web Crawling .......................................................... 371

11.12. Drag and Drop .................................................................................... 37111.12.1. Handling Drops ........................................................................ 37211.12.2. Dropping Items On a Tree ......................................................... 37311.12.3. Dropping Items On a Table ....................................................... 37411.12.4. Accepting Drops ....................................................................... 37511.12.5. Dragging Components .............................................................. 37811.12.6. Dropping on a Component ........................................................ 37911.12.7. Dragging Files from Outside the Browser ................................... 380

11.13. Logging .............................................................................................. 38011.14. JavaScript Interaction .......................................................................... 381

11.14.1. Calling JavaScript ..................................................................... 38211.14.2. Handling JavaScript Function Callbacks ..................................... 382

11.15. Accessing Session-Global Data ........................................................... 38311.15.1. Passing References Around ...................................................... 38411.15.2. Overriding attach() ............................................................... 385

vii

Livro de Vaadin

Page 10: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

11.15.3. ThreadLocal Pattern ................................................................. 38511.16. Server Push ........................................................................................ 386

11.16.1. Installing the Push Support ....................................................... 38711.16.2. Enabling Push for a UI .............................................................. 38711.16.3. Accessing UI from Another Thread ............................................ 38811.16.4. Broadcasting to Other Users ..................................................... 390

11.17. Font Icons ........................................................................................... 39111.17.1. Loading Icon Fonts ................................................................... 39211.17.2. Basic Use ................................................................................ 39211.17.3. Using Font icons in HTML ......................................................... 39311.17.4. Using Font Icons in Other Text ................................................... 39411.17.5. Custom Font Icons ................................................................... 394

Chapter 12. Portal Integration .............................................................................. 39712.1. Overview .............................................................................................. 39712.2. Creating a Portlet Project in Eclipse ........................................................ 39812.3. Portlet UI .............................................................................................. 40012.4. Deploying to a Portal ............................................................................. 401

12.4.1. Portlet Deployment Descriptor ..................................................... 40212.4.2. Liferay Portlet Descriptor ............................................................. 40312.4.3. Liferay Display Descriptor ........................................................... 40312.4.4. Liferay Plugin Package Properties ............................................... 40412.4.5. Using a Single Widget Set ........................................................... 40512.4.6. Building the WAR Package .......................................................... 40512.4.7. Deploying the WAR Package ....................................................... 405

12.5. Installing Vaadin in Liferay ...................................................................... 40612.5.1. Removing the Bundled Installation ............................................... 40612.5.2. Installing Vaadin ......................................................................... 406

12.6. Handling Portlet Requests ..................................................................... 40712.7. Handling Portlet Mode Changes ............................................................. 40812.8. Non-Vaadin Portlet Modes ..................................................................... 41012.9. Vaadin IPC for Liferay ............................................................................ 413

12.9.1. Installing the Add-on ................................................................... 41412.9.2. Basic Communication ................................................................. 41512.9.3. Considerations ........................................................................... 41512.9.4. Communication Through Session Attributes ................................. 41612.9.5. Serializing and Encoding Data .................................................... 41712.9.6. Communicating with Non-Vaadin Portlets ..................................... 418

Part III. Framework de Lado Cliente ................................................................................ 421

Chapter 13. Client-Side Vaadin Development ....................................................... 42313.1. Overview .............................................................................................. 42313.2. Installing the Client-Side Development Environment ................................ 42413.3. Client-Side Module Descriptor ................................................................ 424

13.3.1. Specifying a Stylesheet ............................................................... 42513.3.2. Limiting Compilation Targets ........................................................ 425

13.4. Compiling a Client-Side Module ............................................................. 42513.4.1. Vaadin Compiler Overview .......................................................... 42513.4.2. Compiling in Eclipse ................................................................... 42613.4.3. Compiling with Ant ...................................................................... 42613.4.4. Compiling with Maven ................................................................. 426

13.5. Creating a Custom Widget ..................................................................... 42613.5.1. A Basic Widget ........................................................................... 42613.5.2. Using the Widget ........................................................................ 427

viii

Livro de Vaadin

Page 11: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

13.6. Debugging Client-Side Code .................................................................. 42813.6.1. Launching Development Mode .................................................... 42813.6.2. Launching SuperDevMode .......................................................... 428

Chapter 14. Client-Side Applications ................................................................... 43114.1. Overview .............................................................................................. 43114.2. Client-Side Module Entry-Point .............................................................. 433

14.2.1. Module Descriptor ...................................................................... 43314.3. Compiling and Running a Client-Side Application .................................... 43414.4. Loading a Client-Side Application ........................................................... 434

Chapter 15. Client-Side Widgets .......................................................................... 43715.1. Overview .............................................................................................. 43715.2. GWT Widgets ....................................................................................... 43815.3. Vaadin Widgets ..................................................................................... 438

Chapter 16. Integrating with the Server-Side ....................................................... 43916.1. Overview .............................................................................................. 44016.2. Starting It Simple With Eclipse ............................................................... 443

16.2.1. Creating a Widget ....................................................................... 44416.2.2. Compiling the Widget Set ............................................................ 446

16.3. Creating a Server-Side Component ........................................................ 44616.3.1. Basic Server-Side Component .................................................... 446

16.4. Integrating the Two Sides with a Connector ............................................. 44716.4.1. A Basic Connector ...................................................................... 44716.4.2. Communication with the Server-Side ........................................... 448

16.5. Shared State ........................................................................................ 44816.5.1. Accessing Shared State on Server-Side ...................................... 44816.5.2. Handing Shared State in a Connector .......................................... 44916.5.3. Handling Property State Changes with @OnStateChange ........... 44916.5.4. Delegating State Properties to Widget ......................................... 45016.5.5. Referring to Components in Shared State .................................... 45016.5.6. Sharing Resources ..................................................................... 451

16.6. RPC Calls Between Client- and Server-Side ........................................... 45216.6.1. RPC Calls to the Server-Side ...................................................... 452

16.7. Component and UI Extensions ............................................................... 45316.7.1. Server-Side Extension API .......................................................... 45316.7.2. Extension Connectors ................................................................. 454

16.8. Styling a Widget .................................................................................... 45516.8.1. Determining the CSS Class ......................................................... 45516.8.2. Default Stylesheet ...................................................................... 456

16.9. Component Containers .......................................................................... 45616.10. Advanced Client-Side Topics ................................................................ 456

16.10.1. Client-Side Processing Phases .................................................. 45616.11. Creating Add-ons ................................................................................ 457

16.11.1. Exporting Add-on in Eclipse ...................................................... 45816.11.2. Building Add-on with Ant ........................................................... 458

16.12. Migrating from Vaadin 6 ....................................................................... 46316.12.1. Quick (and Dirty) Migration ........................................................ 463

16.13. Integrating JavaScript Components and Extensions ............................... 46316.13.1. Example JavaScript Library ....................................................... 46316.13.2. A Server-Side API for a JavaScript Component .......................... 46516.13.3. Defining a JavaScript Connector ................................................ 46616.13.4. RPC from JavaScript to Server-Side .......................................... 467

ix

Livro de Vaadin

Page 12: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Part IV. Vaadin Add-ons ................................................................................................. 469

Chapter 17. Using Vaadin Add-ons ...................................................................... 47117.1. Overview .............................................................................................. 47117.2. Downloading Add-ons from Vaadin Directory ........................................... 472

17.2.1. Compiling Widget Sets with an Ant Script ..................................... 47217.3. Installing Add-ons in Eclipse with Ivy ...................................................... 47217.4. Using Add-ons in a Maven Project .......................................................... 474

17.4.1. Adding a Dependency ................................................................ 47417.4.2. Compiling the Project Widget Set ................................................ 47617.4.3. Enabling Widget Set Compilation ................................................. 476

17.5. Troubleshooting ..................................................................................... 477

Chapter 18. Vaadin Charts ................................................................................... 47918.1. Overview .............................................................................................. 47918.2. Installing Vaadin Charts ......................................................................... 48118.3. Basic Use ............................................................................................. 482

18.3.1. Displaying Multiple Series ........................................................... 48318.3.2. Mixed Type Charts ...................................................................... 48418.3.3. Chart Themes ............................................................................ 485

18.4. Chart Types .......................................................................................... 48518.4.1. Line and Spline Charts ............................................................... 48518.4.2. Area Charts ............................................................................... 48618.4.3. Column and Bar Charts .............................................................. 48618.4.4. Error Bars .................................................................................. 48718.4.5. Box Plot Charts .......................................................................... 48818.4.6. Scatter Charts ............................................................................ 49018.4.7. Bubble Charts ............................................................................ 49218.4.8. Pie Charts ................................................................................. 49418.4.9. Gauges ..................................................................................... 49618.4.10. Area and Column Range Charts ................................................ 49718.4.11. Polar, Wind Rose, and Spiderweb Charts ................................... 49818.4.12. Funnel Charts .......................................................................... 50018.4.13. Waterfall Charts ........................................................................ 501

18.5. Chart Configuration ............................................................................... 50318.5.1. Plot Options ............................................................................... 50418.5.2. Axes .......................................................................................... 50418.5.3. Legend ...................................................................................... 505

18.6. Chart Data ............................................................................................ 50518.6.1. List Series .................................................................................. 50618.6.2. Generic Data Series ................................................................... 50618.6.3. Range Series ............................................................................. 50718.6.4. Container Data Series ................................................................ 508

18.7. Advanced Uses ..................................................................................... 50918.7.1. Server-Side Rendering and Exporting .......................................... 509

18.8. Timeline ................................................................................................ 51018.8.1. Graph types ............................................................................... 51118.8.2. Interaction Elements ................................................................... 51218.8.3. Event Markers ............................................................................ 51518.8.4. Efficiency ................................................................................... 51318.8.5. Data Source Requirements ......................................................... 51418.8.6. Events and Listeners .................................................................. 51518.8.7. Configurability ............................................................................ 51618.8.8. Localization ................................................................................ 516

x

Livro de Vaadin

Page 13: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

18.8.9. Timeline Tutorial ......................................................................... 517

Chapter 19. Vaadin JPAContainer ........................................................................ 52519.1. Overview .............................................................................................. 52519.2. Installing ............................................................................................... 528

19.2.1. Downloading the Package ........................................................... 52819.2.2. Installation Package Content ....................................................... 52819.2.3. Downloading with Maven ............................................................ 52819.2.4. Including Libraries in Your Project ................................................ 52919.2.5. Persistence Configuration ........................................................... 52919.2.6. Troubleshooting .......................................................................... 531

19.3. Defining a Domain Model ....................................................................... 53219.3.1. Persistence Metadata ................................................................. 532

19.4. Basic Use of JPAContainer .................................................................... 53519.4.1. Creating JPAContainer with JPAContainerFactory ..................... 53519.4.2. Creating and Accessing Entities .................................................. 53719.4.3. Nested Properties ...................................................................... 53819.4.4. Hierarchical Container ................................................................ 539

19.5. Entity Providers ..................................................................................... 54019.5.1. Built-In Entity Providers ............................................................... 54019.5.2. Using JNDI Entity Providers in JEE6 Environment ........................ 54219.5.3. Entity Providers as Enterprise Beans ........................................... 542

19.6. Filtering JPAContainer .......................................................................... 54319.7. Querying with the Criteria API ................................................................ 543

19.7.1. Filtering the Query ...................................................................... 54419.7.2. Compatibility .............................................................................. 545

19.8. Automatic Form Generation ................................................................... 54519.8.1. Configuring the Field Factory ...................................................... 54519.8.2. Using the Field Factory ............................................................... 54519.8.3. Master-Detail Editor .................................................................... 547

19.9. Using JPAContainer with Hibernate ........................................................ 54719.9.1. Lazy loading .............................................................................. 54719.9.2. The EntityManager-Per-Request pattern ...................................... 54819.9.3. Joins in Hibernate vs EclipseLink ................................................ 549

Chapter 20. Mobile Applications with TouchKit ................................................... 55120.1. Overview .............................................................................................. 55220.2. Considerations Regarding Mobile Browsing ............................................ 554

20.2.1. Mobile Human Interface .............................................................. 55420.2.2. Bandwidth and Performance ....................................................... 55420.2.3. Mobile Features ......................................................................... 55520.2.4. Compatibility .............................................................................. 555

20.3. Installing Vaadin TouchKit ...................................................................... 55520.3.1. Installing as Ivy Dependency ....................................................... 55520.3.2. Installing the Zip Package ........................................................... 55620.3.3. Defining the Maven Dependency ................................................. 556

20.4. Importing the Vornitologist Demo ............................................................ 55620.5. Creating a New TouchKit Project ............................................................ 557

20.5.1. Using the Maven Archetype ........................................................ 55720.5.2. Starting from a New Eclipse Project ............................................. 558

20.6. Elements of a TouchKit Application ......................................................... 55820.6.1. The Servlet Class ....................................................................... 55920.6.2. Defining Servlet and UI with web.xml Deployment Descriptor ...... 55920.6.3. TouchKit Settings ........................................................................ 560

xi

Livro de Vaadin

Page 14: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

20.6.4. The UI ....................................................................................... 56120.6.5. Mobile Widget Set ...................................................................... 56220.6.6. Mobile Theme ............................................................................ 562

20.7. Mobile User Interface Components ......................................................... 56420.7.1. NavigationView ......................................................................... 56520.7.2. Toolbar ..................................................................................... 56620.7.3. NavigationManager .................................................................. 56620.7.4. NavigationButton ..................................................................... 56820.7.5. Popover .................................................................................... 57020.7.6. SwipeView ................................................................................ 57320.7.7. Switch ...................................................................................... 57420.7.8. VerticalComponentGroup ......................................................... 57520.7.9. HorizontalButtonGroup ............................................................ 57620.7.10. TabBarView ............................................................................. 57720.7.11. EmailField ............................................................................... 57820.7.12. NumberField ........................................................................... 57820.7.13. UrlField ................................................................................... 579

20.8. Advanced Mobile Features .................................................................... 57920.8.1. Providing a Fallback UI ............................................................... 57920.8.2. Geolocation ............................................................................... 58020.8.3. Storing Data in the Local Storage ................................................ 58220.8.4. Uploading Content ...................................................................... 583

20.9. Offline Mode ......................................................................................... 58620.9.1. Enabling the Cache Manifest ....................................................... 58720.9.2. Enabling Offline Mode ................................................................ 58720.9.3. The Offline User Interface ........................................................... 58720.9.4. Sending Data to Server ............................................................... 58720.9.5. The Offline Theme ...................................................................... 588

20.10. Building an Optimized Widget Set ......................................................... 58820.10.1. Generating the Widget Map ....................................................... 58820.10.2. Defining the Widget Loading Style ............................................. 58920.10.3. Applying the Custom Widget Map Generator .............................. 58920.10.4. Deployment .............................................................................. 590

20.11. Testing and Debugging on Mobile Devices ............................................ 59020.11.1. Debugging ............................................................................... 590

Chapter 21. Vaadin TestBench ............................................................................. 59121.1. Overview .............................................................................................. 59121.2. Installing Vaadin TestBench .................................................................... 594

21.2.1. Test Development Setup ............................................................. 59421.2.2. A Distributed Testing Environment ............................................... 59521.2.3. Installation Package Contents ..................................................... 59621.2.4. Example Contents ...................................................................... 59721.2.5. Installing Browser Drivers ........................................................... 59821.2.6. Test Node Configuration .............................................................. 598

21.3. Preparing an Application for Testing ........................................................ 59921.4. Developing JUnit Tests .......................................................................... 600

21.4.1. Basic Test Case Structure ........................................................... 60021.4.2. Running JUnit Tests in Eclipse ..................................................... 602

21.5. Creating a Test Case ............................................................................. 60321.5.1. Test Setup .................................................................................. 60321.5.2. Basic Test Case Structure ........................................................... 60421.5.3. Creating and Closing a Web Driver .............................................. 605

21.6. Querying Elements ................................................................................ 606

xii

Livro de Vaadin

Page 15: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

21.6.1. Generating Queries with Debug Window ...................................... 60721.6.2. Querying Elements by Component Type ($) ................................. 60721.6.3. Non-Recursive Component Queries ($$) ..................................... 60721.6.4. Element Classes ........................................................................ 60821.6.5. ElementQuery Objects .............................................................. 60821.6.6. Query Terminators ...................................................................... 608

21.7. Element Selectors ................................................................................. 60821.7.1. Selector Robustness .................................................................. 60921.7.2. Finding by ID .............................................................................. 60921.7.3. Finding by Vaadin Selector .......................................................... 61021.7.4. Finding by CSS Class ................................................................. 610

21.8. Special Test Features ............................................................................ 61121.8.1. Waiting for Vaadin ....................................................................... 61121.8.2. Testing Tooltips ........................................................................... 61121.8.3. Scrolling .................................................................................... 61221.8.4. Testing Notifications .................................................................... 61221.8.5. Testing Context Menus ................................................................ 61221.8.6. Profiling Test Execution Time ....................................................... 613

21.9. Creating Maintainable Tests ................................................................... 61521.9.1. The Page Object Pattern ............................................................. 615

21.10. Taking and Comparing Screenshots ..................................................... 61721.10.1. Screenshot Parameters ............................................................ 61721.10.2. Taking Screenshots on Failure ................................................... 61821.10.3. Taking Screenshots for Comparison ........................................... 61821.10.4. Practices for Handling Screenshots ........................................... 62121.10.5. Known Compatibility Problems .................................................. 621

21.11. Running Tests ..................................................................................... 62121.11.1. Running Tests with Ant .............................................................. 62121.11.2. Running Tests with Maven ......................................................... 622

21.12. Running Tests in a Distributed Environment .......................................... 62321.12.1. Running Tests Remotely ........................................................... 62321.12.2. Starting the Hub ....................................................................... 62421.12.3. Node Service Configuration ...................................................... 62421.12.4. Starting a Grid Node ................................................................. 62621.12.5. Mobile Testing .......................................................................... 627

21.13. Headless Testing ................................................................................. 62721.13.1. Basic Setup for Running Headless Tests .................................... 62721.13.2. Running Headless Tests in a Distributed Environment ................. 628

21.14. Known Issues ..................................................................................... 62821.14.1. Testing the LoginForm ............................................................... 62821.14.2. Running Firefox Tests on Mac OS X ........................................... 629

A. Songs of Vaadin ...................................................................................................... 631Índice Remissivo ........................................................................................................... 635

xiii

Livro de Vaadin

Page 16: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

xiv

Page 17: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

PrefácioEste livro fornece uma visão geral do framework Vaadin e abrange os tópicos mais importantesque você pode encontrar durante o desenvolvimento de aplicações Vaadin. A documentaçãomais detalhada das classes individuais, interfaces e métodos é dada na API de referência Vaadin.

Esta edição aborda principalmente Vaadin 7.2, lançado em maio de 2014. A versão inclui suportepara ícones de fontes e layouts responsivos. No lado cliente, a manipulação de mudanças deestado tornou-se mais fácil com a anotação @OnStateChange. Além disso, o futuro tema Valopara Vaadin 7.3 é apresentado.

Além das mudanças no núcleo do framework, esta edição apresenta documentação para osadd-ons TestBench 4 e TouchKit 4, que ainda não foram lançados no momento da escrita. Oscapítulos atualizados são baseados em versões pré-lançamento dos add-ons, por isso as versõesfinais podem ter algumas mudanças.

Escrever este manual é um trabalho contínuo e raramente está completamente atualizado como produto de evolução rápida. Alguns recursos podem não estar incluídos neste livro ainda. Paraa versão mais atual, consulte a edição on-line disponível em http://vaadin.com/book.Vocêtambém pode encontrar versões em PDF e EPUB do livro lá, além de outras versões maisamigáveis a ferramentas de pesquisa que o livro impresso. O índice do livro está incompleto eserá expandido mais tarde. A edição web também tem alguns conteúdos adicionais, como códigode exemplo e seções adicionais que você pode precisar ao desenvolver software em cenáriosreais. O objetivo da edição impressa ligeiramente abreviada é mais ser um livro didáticointrodutório para Vaadin, e ainda caber no seu bolso.

Além disso, muitas funcionalidades de Vaadin 7 são apresentadas como mini-tutoriais, que estãodisponíveis no Wiki Vaadin https://vaadin.com/wiki/-/wiki/Main/Vaadin+7.

1. Para Quem é Este Livro?

Este livro é destinado a desenvolvedores de software que usam, ou estão considerando apossibilidade de usar, Vaadin para desenvolver aplicações web.

O livro pressupõe que você tenha alguma experiência com programação em Java. Porém, senão tiver, pelo menos é tão fácil começar a aprender Java com Vaadin como com qualquer outroframework de UI. Nenhum conhecimento de AJAX é necessário, uma vez que ele está bemescondido do desenvolvedor.

Você pode já ter utilizado alguns frameworks de interface de usuário em Java voltados paradesktops, como AWT, Swing, SWT ou uma biblioteca como Qt para C++. Tal conhecimento éútil para compreender o escopo do Vaadin, o modelo de programação orientada a eventos, eoutros conceitos comuns de frameworks de interface do usuário (UI), mas não é obrigatório.

Se você não tem um Web Designer à disposição, saber o básico de HTML e CSS pode ajudarpara que você possa desenvolver temas de apresentação para a sua aplicação. Uma breveintrodução a CSS é fornecida. Conhecimento do Google Web Toolkit (GWT) pode ser útil sevocê desenvolver ou integrar novos componentes ao lado cliente.

2. Organização Deste Livro

O Livro de Vaadin dá uma introdução sobre o que o Vaadin é e como usá-lo para desenvolveraplicações web.

xvBook of Vaadin

Page 18: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Parte I: Introdução

Capítulo 1, IntroduçãoO capítulo apresenta uma introdução à arquitetura de aplicação suportada pelo Vaadin,às idéias de projeto principais por trás do framework e algum background histórico.

Capítulo 2, Começando com VaadinEste capítulo fornece instruções práticas para a instalação do Vaadin e um conjuntode ferramentas de referência, incluindo o plugin Vaadin para Eclipse, como executare depurar os demos, e como criar o seu próprio projeto de aplicação na IDE Eclipse.

Capítulo 3, ArquiteturaEste capítulo apresenta uma introdução à arquitetura do Vaadin e suas principaistecnologias, incluindo AJAX, Google Web Toolkit, e programação orientada a eventos.

Parte II: Framework Lado Servidor

Capítulo 4, Escrevendo uma Aplicação Web de Lado ServidorEste capítulo apresenta todo o conhecimento prático necessário para a criação deaplicações com Vaadin, tais como gerenciamento de janelas, ciclo de vida deaplicativos, implantação em container servlet, e tratamento de eventos, erros erecursos.

Capítulo 5, User Interface ComponentsEste capítulo apresenta essencialmente a documentação de referência para todos osprincipais componentes de interface de usuário em Vaadin e suas características maissignificativas. O texto dá exemplos de utilização para cada um dos componentes.

Capítulo 6, Managing LayoutEste capítulo descreve os componentes de layout, que são usados para gerenciar olayout da interface do usuário, assim como em qualquer framework de aplicaçõesdesktop.

Capítulo 7, Visual User Interface Design with EclipseEste capítulo fornece instruções para utilizar o editor visual para Eclipse, que estáincluso no plugin Vaadin para a IDE Eclipse.

Capítulo 8, ThemesEste capítulo apresenta uma introdução para Cascading Style Sheets (CSS) e explicacomo você pode usá-los para construir temas visuais personalizados para suaaplicação.

Capítulo 9, Binding Components to DataEste capítulo apresenta uma visão geral do modelo de dados implementado no Vaadin,que consiste de propriedades, itens e containers.

Capítulo 10, Vaadin SQLContainerEste capítulo fornece documentação para o SQLContainer, que permite a ligação decomponentes Vaadin a consultas SQL.

Capítulo 11, Advanced Web Application TopicsEste capítulo apresenta muitos tópicos especiais que são normalmente necessáriosem aplicações, tais como a abertura de novas janelas do navegador, a incorporaçãode aplicações em páginas web regulares, gerenciamento de recursos em baixo nível,teclas de atalho, depuração, etc.

Organização Deste Livroxvi

Prefácio

Page 19: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Capítulo 12, Portal IntegrationEste capítulo descreve o desenvolvimento de aplicações Vaadin como portlets, quevocê pode implantar em qualquer portal que suporte Java Portlet API 2.0 (JSR-286).O capítulo também descreve o suporte especial à Liferay e os add-ons Painel deControle, IPC, e WSRP.

Parte III: Framework Lado Cliente

Capítulo 13, Client-Side Vaadin DevelopmentEste capítulo apresenta uma introdução à criação e desenvolvimento de aplicaçõese widgets do lado cliente, incluindo instalação, compilação e depuração.

Capítulo 14, Client-Side ApplicationsEste capítulo descreve como desenvolver aplicações do lado cliente e como integrá-los com um serviço de back-end.

Capítulo 15, Client-Side WidgetsEste capítulo descreve os widgets internos (componentes do lado cliente) disponíveispara o desenvolvimento do lado cliente. Os widgets internos incluem widgets GoogleWeb Toolkit, bem como widgets Vaadin.

Capítulo 16, Integrating with the Server-SideEste capítulo descreve como integrar widgets do lado cliente com seus correspondentesdo lado servidor para fins de criação de novos componentes do lado servidor. Ocapítulo aborda também a integração de componentes em JavaScript.

Parte IV: Add-ons Vaadin

Capítulo 17, Using Vaadin Add-onsEste capítulo fornece instruções para baixar e instalar add-ons do Diretório Vaadin.

Capítulo 18, Vaadin ChartsEste capítulo documenta o uso do add-on Vaadin Charts para criação de gráficosinterativos com vários tipos de diagramas. O add-on inclui os componentes Chart eTimeline.

Capítulo 19, Vaadin JPAContainerEste capítulo apresenta a documentação do add-on JPAContainer, que permite aligação de componentes Vaadin diretamente a bancos de dados relacionais e outrasbases de dados que usem Java Persistence API (JPA).

Capítulo 20, Mobile Applications with TouchKitEste capítulo apresenta exemplos e documentação de referência para o uso do add-on Vaadin TouchKit para o desenvolvimento de aplicações móveis.

Capítulo 21, Vaadin TestBenchEste capítulo apresenta a documentação completa do uso da ferramenta VaadinTestBench para gravação e execução de testes de regressão de interface de usuárioem aplicações Vaadin.

Apêndice A, Songs of VaadinFundo mitológico do nome Vaadin.

xviiOrganização Deste Livro

Prefácio

Page 20: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

3. Material Suplementar

O site do Vaadin oferece bastante material que pode ajudar você a entender o que o Vaadin é,o que você pode fazer com ele, e como você pode fazê-lo.

Aplicações de DemonstraçãoA aplicação mais importante para a demonstração do Vaadin é o Sampler, quedemonstra a utilização de todos os componentes e as funcionalidades básicas. Vocêpode executá-lo on-line em http://demo.vaadin.com/ ou baixá-lo como um WAR napágina de download do Vaadin.

A maioria dos exemplos de código neste livro e muitos outros podem ser encontradoson-line em: http://demo.vaadin.com/book-examples-vaadin7/book/.

Folha de Acesso RápidoA folha de acesso rápido ilustra o relacionamento de hierarquia das classes e interfacesde UI e de ligação de dados. Você pode baixá-la em http://vaadin.com/book.

Cartão de ReferênciaO cartão de referência DZone de seis páginas dá uma visão geral para odesenvolvimento de aplicações com Vaadin. Ele inclui um diagrama de classes einterfaces de UI e de ligação de dados. Você pode encontrar mais informações sobreele em https://vaadin.com/refcard.

Tutorial Address Book (Catálogo de Endereços)O Address Book (Catálogo de Endereços) é uma aplicação de amostra acompanhadapor um tutorial que dá instruções detalhadas passo-a-passo para a criação de umaaplicação web da vida real com Vaadin. Você pode encontrar o tutorial no site doproduto.

Site do DesenvolvedorO Site do Desenvolvedor Vaadin, disponível em http://dev.vaadin.com/, oferece váriosrecursos on-line, tais como um exemplo de um sistema de ingressos, a wiki dedesenvolvimento, repositórios de código fonte, cronograma de atividades, marcos dedesenvolvimento, e assim por diante.

A wiki fornece instruções para desenvolvedores, especialmente para aqueles quedesejam fazer check-out e compilar o Vaadin a partir do repositório de código fonte.Os artigos técnicos lidam com a integração de aplicações Vaadin com vários sistemas,tais como JSP, Maven, Spring, Hibernate e portais. A wiki também oferece respostasàs perguntas mais frequentes.

Documentação OnlineVocê pode ler este livro online em http://vaadin.com/book. Bastante material adicional,incluindo tutoriais técnicos, respostas às perguntas mais frequentes e outrasdocumentações também estão disponíveis no Site do Vaadin.

4. Suporte

Preso em um problema? Não há necessidade de perder o seu cabelo por isso. A comunidadede desenvolvedores do framework Vaadin e a companhia Vaadin oferecem suporte a todas assuas necessidades.

Material Suplementarxviii

Prefácio

Page 21: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Fórum Comunitário de SuporteVocê pode encontrar o fórum comunitário do usuário e desenvolvedor emhttp://vaadin.com/forum. Por favor, use o fórum para discutir qualquer problema quevocê possa encontrar, desejos por funcionalidades, e assim por diante. A respostapara seus problemas pode já estar nos arquivos do fórum. Então, pesquisar asdiscussões é sempre a melhor maneira de começar.

Reportar BugsSe você encontrar um possível bug no Vaadin, nas aplicações de demonstração, ouna documentação, por favor, reporte-o preenchendo um ticket no site do desenvolvedorVaadin em http://dev.vaadin.com/. Você pode querer verificar os tickets existentesantes de adicionar um novo. Você pode preencher um ticket para pedir uma novafuncionalidade também, ou sugerir modificações para uma funcionalidade existente.

Suporte ComercialVaadin oferece suporte comercial completo e serviços de treinamento para oFramework Vaadin e produtos relacionados. Leia mais sobre os produtos comerciaisem http://vaadin.com/pro para mais detalhes.

5. Sobre o Autor

Marko Grönroos é um escritor e desenvolvedor de software profissional que trabalha na VaadinLtd, em Turku, na Finlândia. Ele esteve envolvido no desenvolvimento de aplicações web desde1994 e já trabalhou em diversos frameworks de desenvolvimento de aplicações em C, C++ eJava. Ele tem estado ativo em muitos projetos de software de código aberto e possui Mestradoem Ciência da Computação pela Universidade de Turku.

6. Agradecimentos

Grande parte do livro é o resultado do trabalho próximo ao time de desenvolvimento na VaadinLtd. Joonas Lehtinen, CEO da Vaadin Ltd, escreveu o primeiro esboço do livro, que se tornoua base para os dois primeiros capítulos. Desde então, Marko Grönroos tornou-se o principalautor e editor. A equipe de desenvolvimento tem contribuído em várias passagens, respondendoinúmeras perguntas técnicas, revisando o manual, e fazendo muitas correções.

Os colaboradores são (em ordem cronológica aproximada):

Joonas LehtinenJani LaaksoMarko GrönroosJouni KoivuviitaMatti TahvonenArtur SignellMarc EnglundHenri SaraJonatan KronqvistMikael Grankvist (TestBench)Teppo Kurki (SQLContainer)Tomi Virtanen (Calendar)Risto Yrjänä (Calendar)John Ahlroos (Timeline)Petter Holmström (JPAContainer)Leif Åstrand

xixSobre o Autor

Prefácio

Page 22: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

7. Sobre a Vaadin Ltd

Vaadin Ltd é uma empresa finlandesa de software especializada na concepção e desenvolvimentode Rich Internet Applications. A companhia oferece planejamento, implementação e serviços deapoio para os projetos de seus clientes de software, bem como o desenvolvimento de softwarepor contrato. O Framework Vaadin, anteriormente conhecido como Toolkit IT Mill, é o carro-chefedo produto open source da companhia, para o qual presta serviços de desenvolvimento e suportecomercial.

Sobre a Vaadin Ltdxx

Prefácio

Page 23: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Parte I. IntroduçãoEsta parte vem em três capítulos que apresentam as idéias básicas por trás do Vaadin e seus dois modelosde programação, de lado servidor e de lado cliente. Além disso, descreve sua instalação e dá uma visãogeral de sua arquitetura.

Page 24: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br
Page 25: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 1

Introdução

1.1. Visão Geral .............................................................................................. 231.2. Exemplo de Aplicação Passo a Passo .................................................... 251.3. Suporte à IDE Eclipse ............................................................................. 261.4. Metas e Filosofia ..................................................................................... 271.5. Conhecimento ......................................................................................... 27

Este capítulo apresenta uma breve introdução ao desenvolvimento de software com Vaadin.Também tentamos dar algumas dicas sobre a filosofia de projeto por trás do Vaadin e sua história.

1.1. Visão Geral

Vaadin é um framework de desenvolvimento de aplicações web em Java que foi projetado paratornar a criação e manutenção de interfaces de usuário web de alta qualidade fácil. Vaadinsuporta dois modelos de programação diferentes: no lado servidor e no lado cliente. O modelode programação orientado pelo servidor é o mais poderoso. Ele permite que você esqueça aweb e programe interfaces de usuário de forma muito parecida como você programa umaaplicação desktop com toolkits Java convencionais como AWT, Swing ou SWT. Porém, maisfácil.

Enquanto a programação web tradicional é uma maneira divertida de passar o tempo aprendendonovas tecnologias, você provavelmente quer ser produtivo e concentrar-se na lógica da aplicação.O framework Vaadin se encarrega do gerenciamento da interface do usuário no navegador eda comunicação com AJAX entre o navegador e o servidor. Com a abordagem Vaadin, vocênão precisa aprender e lidar diretamente com as tecnologias do navegador, como HTML ouJavaScript.

23Book of Vaadin

Page 26: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 1.1. Arquitetura da Aplicação Vaadin

Figura 1.1, “Arquitetura da Aplicação Vaadin” ilustra as arquiteturas básicas de aplicações webfeitas com Vaadin. A arquitetura da aplicação do lado servidor é composta do framework de ladoservidor e de uma engine de lado cliente. A engine é executada no navegador como códigoJavaScript, apresentando a interface do usuário e entregando sua interação para o servidor. Alógica da UI de uma aplicação é executada como um Servlet Java em um servidor de aplicaçõesJava.

Como a engine do lado cliente é executada como JavaScript no navegador, não são necessáriosplugins para utilizar aplicações feitas com Vaadin. Isso dá uma vantagem sobre os frameworksbaseados em Flash, Applets Java e outros plugins. Vaadin conta com o suporte ao Google WebToolkit para uma ampla variedade de navegadores, de modo que o desenvolvedor não precisase preocupar com o suporte ao navegador.

Como o HTML, JavaScript e outras tecnologias de navegadores são essencialmente invisíveisà lógica da aplicação, você pode pensar no navegador web como sendo apenas uma plataformathin client. Um thin client exibe a interface do usuário e comunica eventos do usuário para oservidor em um baixo nível. A lógica de controle da interface do usuário é executada em umservidor Java web, juntamente com a sua lógica de negócios. Em contraste, uma arquiteturacliente-servidor normal, com uma aplicação cliente dedicada, incluiria uma série de comunicaçõesespecíficas da aplicação entre cliente e servidor. Remover substancialmente a camada dainterface de usuário da arquitetura da aplicação torna a nossa abordagem bastante eficaz.

Por trás do modelo de desenvolvimento orientado pelo servidor, Vaadin faz o melhor uso deAJAX (Javascript Assíncrono e XML, veja Secção 3.2.3, “AJAX” para uma descrição) e detécnicas que tornam possível a criação de Aplicações de Internet Rica (RIA - Rich InternetApplication) que são tão ágeis e interativas quanto aplicações desktop.

Além do desenvolvimento de aplicações Java no lado servidor, você pode desenvolver no ladocliente, fazendo novos widgets em Java, e até mesmo aplicações totalmente no lado cliente,que rodem apenas no navegador. O framework Vaadin de lado cliente inclui o Google WebToolkit (GWT), que fornece um compilador de Java para JavaScript, que roda no navegador,bem como um framework de interface de usuário completo. Com esta abordagem, Vaadin épuro Java em ambos os lados.

Vaadin usa uma engine de lado cliente para apresentar a interface de usuário de aplicações delado servidor no navegador.Todas as comunicações cliente-servidor ficam bem escondidas sobo capô. Vaadin é projetado para ser extensível, e você realmente pode usar quaisquer widgetsde terceiros com facilidade, além do conjunto de componentes oferecidos no Vaadin. Na verdade,você pode encontrar centenas de add-ons no Diretório Vaadin.

Visão Geral24

Introdução

Page 27: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O Framework Vaadin define uma separação clara entre aestrutura da interface de usuário e sua aparência, e permiteque você desenvolva-os separadamente. Nossa abordagempara isso é o uso de temas que controlam a aparência comCSS e templates HTML opcionais. Como o Vaadin fornecetemas padrão excelentes, usualmente você não precisa fazermuita customização. Mas você pode, se necessário. Para maisinformações sobre temas, consulte Capítulo 8, Themes.

Esperamos que isso seja o suficiente sobre arquitetura efuncionalidades básicas do Vaadin para agora. Você pode lermais sobre isso depois em Capítulo 3, Arquitetura, ou pulardireto para coisas mais práticas em Capítulo 4, Escrevendouma Aplicação Web de Lado Servidor.

1.2. Exemplo de Aplicação Passo a Passo

Vamos seguir a longa tradição de primeiro dizer "Hello World!" ao aprender um novo frameworkde programação. Primeiro, utilizando a API de lado servidor.

import com.vaadin.server.VaadinRequest;import com.vaadin.ui.Label;import com.vaadin.ui.UI;@Title("Hello Window")public class HelloWorld extends UI {@Overrideprotected void init(VaadinRequest request) {// Criar o layout raiz de conteúdo para a interface de usuárioVerticalLayout content = new VerticalLayout();setContent(content);// Mostra a saudaçãocontent.addComponent(new Label("Hello World!"));}}

Uma aplicação Vaadin tem uma ou mais UIs que estendem a classe com.vaadin.ui.UI. Uma UIé uma parte da página web onde a aplicação Vaadin é executada. Uma aplicação pode termúltiplas UIs na mesma página, especialmente em portais, ou em diferentes janelas ou abas.Elas ficam associadas a uma sessão de usuário. Uma sessão é criada para cada usuário queusa a aplicação. No contexto do nosso "Hello World!", é suficiente saber que a sessão subjacenteé criada quando o usuário acessa pela primeira vez a aplicação ao abrir a página, e o métodoinit() é invocado nesse momento .

No exemplo acima, o título da página, que é mostrado na legenda da janela ou aba do navegador,é definido com uma anotação. O exemplo usa um componente de layout como conteúdo raizda UI, como é o caso da maioria das aplicações Vaadin, que normalmente têm mais de umcomponente. Em seguida, cria um novo componente de interface de usuário Label, que exibeum texto simples, e define o texto para "Hello World!". O label é adicionado ao layout.

O resultado da aplicação Hello World, quando aberta em um navegador, é apresentado emFigura 1.2, “Aplicação Hello World”.

25Exemplo de Aplicação Passo a Passo

Introdução

Page 28: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 1.2. Aplicação Hello World

Para executar o programa, você pode simplesmente empacotá-lo como uma aplicação web emum pacote WAR e instalá-lo em um servidor, como é explicado em Secção 4.8, “Implantandouma Aplicação”.

Desenvolvendo uma aplicação puramente de lado cliente, você poderia escrever um Hello Worldcom a mesma facilidade, e também em Java:

public class HelloWorld implements EntryPoint {@Overridepublic void onModuleLoad() {RootPanel.get().add(new Label("Hello, world!"));}}

Nós não definimos o título aqui, porque ele é geralmente definido na página HTML em que ocódigo é executado. A aplicação seria compilada para JavaScript com o Vaadin Client Compiler(ou GWT Compiler). É mais comum, no entanto, escrever widgets de lado cliente, que podemser utilizados a partir de aplicações Vaadin de lado servidor. Para mais informações sobre odesenvolvimento no lado cliente, consulte Capítulo 13, Client-Side Vaadin Development.

1.3. Suporte à IDE Eclipse

Enquanto o Vaadin não está vinculado a qualquer IDE específica, e você pode de fato usá-lofacilmente sem qualquer IDE, nós fornecemos suporte especial para a IDE Eclipse, que se tornouo ambiente mais utilizado para desenvolvimento em Java. O suporte é fornecido no Plugin Vaadinpara Eclipse, que ajuda você a:

• Criar novos projetos Vaadin

• Criar temas customizados

• Criar widgets customizados

• Criar componentes compostos com um editor visual

• Atualizar facilmente para uma versão mais recente da biblioteca Vaadin

Utilizar o Plugin Vaadin para Eclipse é a forma recomendada de instalar Vaadin para odesenvolvimento. Baixar o pacote de instalação que contém os JARs ou definir Vaadin comouma dependência no Maven também é possível.

A instalação e a atualização do plugin do Eclipse são cobertos em Secção 2.4, “Instalando oPlugin Vaadin para Eclipse”, e a criação de um novo projeto Vaadin usando o plugin em

Suporte à IDE Eclipse26

Introdução

Page 29: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Secção 2.5.1, “Criando o Projeto”.Veja Secção 8.5, “Creating a Theme in Eclipse”, Secção 16.2,“Starting It Simple With Eclipse”, e Capítulo 7, Visual User Interface Design with Eclipse parainstruções sobre como utilizar as diferentes funcionalidades do plugin.

1.4. Metas e Filosofia

Simplificando, a ambição do Vaadin é ser a melhor ferramenta possível, quando se trata decriação de interfaces de usuário web para aplicações de negócios. É fácil de adotar, como eleé projetado para suportar tanto programadores iniciantes quanto avançados, bem comoespecialistas em usabilidade e designers gráficos.

Ao projetar o Vaadin, temos seguido a filosofia inscrita nas seguintes regras.

1.4.1. Ferramenta certa para o propósito certo

Como as nossas metas são altas, o foco deve ser claro. Vaadin é projetado para a criação deaplicações web. Ele não foi projetado para a criação de sites ou demonstrações de propaganda.Você pode achar, por exemplo, JSP/JSF ou Flash mais adequados para tais fins.

1.4.2. Simplicidade e facilidade de manutenção

Optamos por ressaltar a robustez, simplicidade e facilidade de manutenção. Trata-se de seguiras melhores práticas bem estabelecidas nos frameworks de interface de usuário e garantir quenossa implementação representa uma solução ideal para o seu propósito, sem desordem ouinchaço.

1.4.3. XML não é projetado para programação

A Web é inerentemente centrada a documentos e muito ligada à apresentação declarativa deinterfaces de usuário. O framework Vaadin liberta o programador dessas limitações. É muitomais natural criar interfaces de usuário programando-as do que definindo-as em templatesdeclarativos, que não são flexíveis o suficiente para a interação complexa e dinâmica do usuário.

1.4.4. Ferramentas não devem limitar o seu trabalho

Não deve haver limites para o que você pode fazer com o framework: se por algum motivo oscomponentes da interface de usuário não suportam o que você precisa alcançar, deve ser fáciladicionar novos componentes para a sua aplicação. Quando você precisar criar componentesnovos, o papel do framework é fundamental: ele facilita a criação de componentes reutilizáveisque são fáceis de manter.

1.5. Conhecimento

O framework Vaadin não foi escrito da noite para o dia. Depois de trabalhar com interfaces deusuário web desde o início da Web, um grupo de desenvolvedores se juntou no ano 2000 paraformar o IT Mill. A equipe teve o desejo de desenvolver um novo paradigma de programaçãoque apoiaria a criação de interfaces de usuário reais para aplicações reais utilizando umalinguagem de programação real.

A biblioteca foi originalmente chamada Millstone Library. A primeira versão foi usada em umaaplicação de produção grande que o IT Mill concebeu e implementou para uma empresafarmacêutica internacional. O IT Mill fez a aplicação no ano 2001 e ela ainda está em uso. Desde

27Metas e Filosofia

Introdução

Page 30: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

então, a empresa já produziu dezenas de aplicações de negócios grandes com a biblioteca eela provou sua capacidade de resolver problemas difíceis com facilidade.

A geração seguinte da biblioteca, Toolkit IT Mill Release 4, foi lançada em 2006. Ela introduziuuma engine de apresentação baseada em AJAX totalmente nova. Isso permitiu o desenvolvimentode aplicações AJAX, sem a necessidade de se preocupar com a comunicação entre o cliente eo servidor.

1.5.1. Release 5 Aberta

O Toolkit IT Mill 5, lançado inicialmente no final de 2007, deu um passo significativo no AJAX.A renderização da interface de usuário no lado cliente foi totalmente rescrita usando GWT, oGoogle Web Toolkit.

O Toolkit IT Mill 5 introduziu muitas melhorias significativas tanto na API do lado servidor quantona funcionalidade. Rescrever a engine do lado cliente com GWT permitiu o uso de Java, tantono lado cliente quanto no servidor. A transição de JavaScript para GWT tornou o desenvolvimentoe integração de componentes customizados e a customização de componentes existentes muitomais fácil do que antes. Também permitiu a fácil integração de componentes GWT existentes.A adoção de GWT no lado cliente não causou, por si só, qualquer alteração na API do ladoservidor, porque GWT é uma tecnologia de navegador que está bem escondida por trás da API.A tematização também foi completamente revista no Toolkit IT Mill 5.

A Release 5 foi publicada sob a Licença Apache 2, uma licença de código aberto sem restriçõespara expandir rapidamente a base de usuários e tornar a formação de uma comunidade dedesenvolvedores possível.

1.5.2. Nascimento do Release Vaadin 6

Toolkit IT Mill foi rebatizado para Framework Vaadin, ou Vaadin em suma, na primavera de 2009.Posteriormente, IT Mill, a companhia, também foi rebatizada como Vaadin Ltd. Vaadin significauma rena adulta fêmea semi-domesticada das montanhas na Finlândia.

Com o Vaadin 6, o número de desenvolvedores que usam o framework explodiu. Juntamentecom o lançamento, o Plugin Vaadin para Eclipse foi lançado, ajudando a criação de projetosVaadin. A introdução do Diretório Vaadin no início de 2010 deu-lhe um novo impulso, com onúmero de componentes disponíveis multiplicado quase da noite para o dia. Muitos doscomponentes originalmente experimentais têm, desde então, amadurecido e agora são usadospor milhares de desenvolvedores. Em 2013, estamos vendo um enorme crescimento noecossistema em torno do Vaadin. O tamanho da comunidade de usuários, pelo menos se medidopela atividade do fórum, já ultrapassou os frameworks concorrentes de lado servidor e até mesmoGWT.

1.5.3. A Importante Revisão com Vaadin 7

O Vaadin 7 é uma revisão importante que muda a API Vaadin muito mais do que o Vaadin 6 fez.É certamente mais orientado à web que Vaadin 6. Estamos fazendo todo o possível para ajudara ascensão do Vaadin no universo web. Parte desse trabalho é fácil e quase rotineiro - correçãode bugs e implementação de funcionalidades. Mas ir além também requer pé firme. Esse foi umdos objetivos do Vaadin 7 - redesenhar o produto para que a nova arquitetura permita ao Vaadinalcançar muitos desafios de longa data. Muitas das mudanças requereram romper acompatibilidade da API com Vaadin 6, especialmente no lado cliente. Mas elas foram feitas comum forte desejo de evitar carregar peso legado desnecessário para um futuro distante. Vaadin

Release 5 Aberta28

Introdução

Page 31: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

7 inclui uma camada de compatibilidade para tornar sua adoção em aplicações existentes maisfácil.

A inclusão do Google Web Toolkit no Vaadin 7 é um desenvolvimento significativo, uma vez queisso significa que agora fornecemos suporte para GWT também. Quando o Google abriu odesenvolvimento GWT no Verão de 2012, a Vaadin (a companhia) se juntou ao novo comitê dedireção GWT. Como membro do comitê, Vaadin pode trabalhar para o sucesso do GWT comouma fundação da comunidade de desenvolvimento Java web.

29A Importante Revisão com Vaadin 7

Introdução

Page 32: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

30

Page 33: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 2

Começando comVaadin

2.1. Visão Geral .............................................................................................. 312.2. Configurando o Ambiente de Desenvolvimento ...................................... 322.3. Visão Geral das Bibliotecas Vaadin ......................................................... 362.4. Instalando o Plugin Vaadin para Eclipse .................................................. 372.5. Criando e Executando um Projeto com Eclipse ...................................... 412.6. Usando Vaadin com Maven ..................................................................... 502.7. Criando um projeto no IDE NetBeans ..................................................... 522.8. Criando um projeto com IntelliJ IDEA ...................................................... 532.9. Pacote de instalação Vaadin .................................................................... 622.10. Usando Vaadin com Scala ..................................................................... 63

Este capítulo fornece instruções práticas para a instalação do conjunto de ferramentasrecomendadas, as bibliotecas Vaadin e suas dependências, e para criação de um novo projetoVaadin.

2.1. Visão Geral

Você pode desenvolver aplicações Vaadin em praticamente qualquer ambiente dedesenvolvimento que tenha o SDK Java e um container Java Servlet. Vaadin possui suporteespecial para o IDE Eclipse, mas o apoio da comunidade também existe para o IDE NetBeanse o IntelliJ IDEA, e você pode usá-lo com qualquer IDE Java ou sem absolutamente nenhumaIDE.

31Book of Vaadin

Page 34: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Gerenciar Vaadin e outras bibliotecas Java manualmente pode ser entediante. Logo, usar umsistema de build que gerencia as dependências automaticamente é aconselhável. Vaadin édistribuído no repositório central Maven, e pode ser usado com qualquer sistema degerenciamento de build ou de dependências que possam acessar o repositório Maven, tais comoo Ivy ou Gradle, além do Maven.

Vaadin tem uma infinidade de opções de instalação para diferentes IDEs e gerenciadores dedependência. Você também pode instalá-lo a partir de um pacote de instalação:

• Com o IDE Eclipse, utilize o Plugin Vaadin para Eclipse, conforme descrito emSecção 2.4, “Instalando o Plugin Vaadin para Eclipse”

• Com o plugin Vaadin para o IDENetBeans (Secção 2.7, “Criando um projeto no IDENetBeans”) ou IntelliJ IDEA

• Com Maven, Ivy, Gradle, ou outro gerenciador de dependência compatível com Maven,no Eclipse, NetBeans, IDEA, ou usando linha de comando, conforme descrito emSecção 2.6, “Usando Vaadin com Maven”

• Do pacote de instalação, sem gerência de dependência, conforme descrito emSecção 2.9, “Pacote de instalação Vaadin”

2.2. Configurando o Ambiente de Desenvolvimento

Esta seção orienta passo-a-passo a criação de um ambiente de desenvolvimento de referência.Vaadin suporta uma ampla variedade de ferramentas, assim você pode usar qualquer IDE paraescrever o código, quase qualquer servidor web Java para implantar a aplicação, a maioria dosnavegadores da web para usá-lo, e qualquer plataforma de sistema operacional suportado peloJava.

Neste exemplo, usamos o seguinte conjunto de ferramentas:

• Windows, Linux, ou Mac OS X

• Sun Java 2 Standard Edition 6.0 (JDK 1.6 ou mais nova é requerida)

• IDE Eclipse para Desenvolvedores Java EE

• Apache Tomcat 7.0 (Core) ou mais novo

• Browser Mozilla Firefox

• Ferramenta de depuração Firebug (opcional)

• Framework Vaadin

O conjunto de ferramentas de referência acima é uma boa escolha, mas você pode usar quasequalquer ferramenta com que você se sinta confortável.

Se você pretende usar push de servidor, você precisará usar um servidor compatível com JavaEE 7 e com suporte a WebSocket, como Glassfish, TomEE, etc.

Configurando o Ambiente de Desenvolvimento32

Começando com Vaadin

Page 35: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 2.1. Ferramentas de Desenvolvimento e Processo

Figura 2.1, “Ferramentas de Desenvolvimento e Processo” ilustra o conjunto de ferramentas dedesenvolvimento. Você desenvolve sua aplicação como um projeto Eclipse. O projeto deveincluir, além de seu código-fonte, as bibliotecas Vaadin. Também pode incluir temas específicosdo projeto.

Você precisa compilar e implantar um projeto em um contêiner web antes de usá-lo. Você podeimplantar um projeto através do Web Tools Platform (WTP) para Eclipse (incluído no pacoteEclipse EE), que permite a implantação automática de aplicações web a partir do Eclipse. Vocêtambém pode implantar um projeto manualmente em um contêiner, através da criação de umarquivo de aplicação web (WAR).

2.2.1. Instalando o SDK Java

O SDK Java é requerido pelo Vaadin e também pela IDE Eclipse. Vaadin é compatível com Java1.6 e edições posteriores. Java EE 7 é necessário para um suporte adequado ao push de servidorcom WebSockets.

Windows

1. B a i x e S u n J a v a 2 S t a n d a r d E d i t i o n 7 . 0 e mhttp://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Instale o SDK Java, executando o instalador. As opções padrão são suficientes.

Linux / UNIX

A maioria dos sistemas Linux ou tem uma JDK pré-instalada ou permite a instalação através dosistema de gerenciamento de pacotes. Observe, porém, que eles têm a OpenJDK como a

33Instalando o SDK Java

Começando com Vaadin

Page 36: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

implementação Java padrão. Embora seja conhecido que ela funciona com Vaadin epossivelmente também com o conjunto de ferramentas de desenvolvimento, nós não fornecemossuporte a ela.

A respeito do OS X, observe que o JDK 1.6 ou mais recente está incluso no Mac OS X 10.6 oumais recente.

Do contrário:

1. B a i x e S u n J a v a 2 S t a n d a r d E d i t i o n 6 . 0 d ehttp://www.oracle.com/technetwork/java/javase/downloads/

2. Descompacte-o em um diretório base adequado, como /opt. Por exemplo, para a SDKJava, digite (como root ou com sudo em Linux):

# cd /opt# sh (caminho-para-o-pacote-de-instalação)/jdk-7u1-linux-i586.bin

e siga as instruções do instalador.

3. Configure a variável de ambiente JAVA_HOME para apontar para o diretório de instalaçãodo Java. Além disso, inclua o $JAVA_HOME/bin no PATH. Como você faz isso variade acordo com a distribuição do UNIX. Por exemplo, no Linux e utilizando o shell Bash,você pode adicionar linhas como o seguinte no script .bashrc ou .profile, em seudiretório home:

export JAVA_HOME=/opt/jdk1.7.0_01export PATH=$PATH:$HOME/bin:$JAVA_HOME/bin

Você também pode fazer a configuração de todo o sistema em um arquivo como/etc/bash.bashrc, /etc/profile, ou um arquivo equivalente. Se você instalar oApache Ant ou o Maven, você também pode querer configurá-los no path.

Configurações feitas em um arquivo bashrc exigem que você abra uma nova janelado shell. Configurações feitas em um arquivo profile exigem que você faça login nosistema. Você pode, é claro, também dar os comandos no shell atual.

2.2.2. Instalando o IDE Eclipse

Windows

1. Baixe o IDE Eclipse para Desenvolvedores Java EE emhttp://www.eclipse.org/downloads/

2. Descompacte o pacote do IDE Eclipse para um diretório adequado. Você é livre paraescolher qualquer diretório e para usar qualquer descompactador ZIP. Mas nesteexemplo, descompactamos o arquivo ZIP apenas clicando duas vezes sobre ele eselecionando a tarefa "Extrair todos os arquivos" das tarefas de pasta compactada doWindows. No nosso exemplo de instalação, nós usamos C:\dev como diretório dedestino.

O Eclipse está instalado em C:\dev\eclipse, e pode ser iniciado a partir de lá (duplo cliqueem eclipse.exe).

Instalando o IDE Eclipse34

Começando com Vaadin

Page 37: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Linux / OS X / UNIX

Recomendamos que você instale o Eclipse manualmente no Linux e em outros sistemas UNIXcomo se segue.

1. Baixe o Eclipse IDE para Desenvolvedores Java EE a partir dehttp://www.eclipse.org/downloads/

2. Descompacte o pacote Eclipse em um diretório base adequado. É importante se certificarde que não há nenhuma instalação Eclipse velha no diretório de destino. A instalaçãode uma nova versão em cima de um velha provavelmente torna o Eclipse inutilizável.

3. O Eclipse deve ser instalado com uma conta de usuário comum, pois isso torna ainstalação de plugins mais fácil. O Eclipse também armazena algumas configuraçõesdo usuário no diretório de instalação. Para instalar o pacote, digite:

$ tar zxf (caminho para o pacote de instalação)/eclipse-jee-ganymede-SR2-linux-gtk.tar.gz

. Isto irá extrair o pacote em um subdiretório de nome eclipse.

4. Você pode adicionar o diretório de instalação do Eclipse e o subdiretório bin dainstalação do Java SDK no PATH de usuário ou do sistema.

Uma alternativa para o procedimento acima seria usar uma versão do Eclipse disponível atravésdo sistema de gerenciamento de pacotes do seu sistema operacional. No entanto, esta alternativanão é recomendada porque você precisará de permissão de escrita no diretório de instalaçãodo Eclipse para instalar os plugins, e você pode enfrentar problemas de incompatibilidade complugins instalados pelo sistema de gerenciamento de pacotes.

2.2.3. Instalando o Apache Tomcat

O Apache Tomcat é um servidor web Java leve adequado para desenvolvimento e produção.Há muitas formas de instalá-lo, mas aqui simplesmente descompactamos o pacote de instalação.

O Apache Tomcat deve ser instalado com permissões de usuário. Durante o desenvolvimento,você utilizará o Eclipse ou qualquer outro IDE com as permissões de usuário, mas a instalaçãode aplicativos web em um servidor Tomcat instalado no sistema requer permissões deadministrador ou root.

1. Baixe o pacote de instalação:

Apache Tomcat 7.0 (Core Binary Distribution) de http://tomcat.apache.org/

2. Descompacte o pacote Apache Tomcat para um diretório de destino adequado, comoC:\dev (Windows) ou /opt (Linux ou Mac OS X). O diretório home do Apache Tomcatserá C:\dev\apache-tomcat-7.0.x ou /opt/apache-tomcat-7.0.x,respectivamente.

2.2.4. Firefox e Firebug

Vaadin suporta vários navegadores e você pode usar qualquer um deles para o desenvolvimento.Se você pretende criar tema e layout personalizados, ou criar novos componentes, recomendamosque você use o Firefox com Firebug ou o Google Chrome, que foi construído com ferramentasde desenvolvimento semelhantes ao Firebug.

35Instalando o Apache Tomcat

Começando com Vaadin

Page 38: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Utilizando Firebug com Vaadin

Depois de instalar o Firefox, use-o para abrir http://www.getfirebug.com/. Siga as instruções nosite para instalar a última versão estável do Firebug disponível para o navegador. Pode sernecessário permitir que o Firefox instale o plugin, clicando na barra de aviso amarela no topoda janela do navegador.

Após a instalação do Firebug, ele pode ser ativado a qualquer momento a partir da barra deferramentas do Firefox. Figura 2.2, “Depurador Firebug para Firefox” mostra o Firebug em ação.

Figura 2.2. Depurador Firebug para Firefox

A funcionalidade mais importante do Firebug é a inspeção de elementos HTML. Clique com obotão direito do mouse sobre um elemento e selecione Inspect Element with Firebug parainspecioná-lo. Além de árvore HTML, ele também mostra as regras CSS correspondentes aoelemento, que você pode usar para construir temas.Você pode até mesmo editar os estilos CSSem tempo real, para experimentar estilos.

2.3. Visão Geral das Bibliotecas Vaadin

Vaadin vem como um conjunto de bibliotecas JAR, das quais algumas são opcionais oualternativas, dependendo se você estiver desenvolvendo aplicações do lado servidor ou cliente,se você usar componentes add-on, ou usar CSS ou temas Sass.

vaadin-server-7.x.x.jarA principal biblioteca para desenvolvimento de aplicações Vaadin de lado servidor,conforme descrito em Capítulo 4, Escrevendo uma Aplicação Web de Lado Servidor.Ela requer as bibliotecas vaadin-shared e vaadin-themes. Você pode usar

Visão Geral das Bibliotecas Vaadin36

Começando com Vaadin

Page 39: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

vaadin-client-compiled para o desenvolvimento do lado servidor, exceto sevocê precisar de add-ons ou widgets personalizados.

vaadin-shared-7.x.x.jarUma biblioteca compartilhada para desenvolvimento de lado cliente e servidor. Sempreé necessário.

vaadin-client-7.x.x.jarO framework Vaadin de lado cliente, incluindo API básica GWT e Widgets específicosdo Vaadin. Ele é necessário quando se utiliza o vaadin-client-compiler paracompilar os módulos do lado cliente. Ele não é necessário se você usou apenas oframework de lado servidor com a engine de lado cliente pré-compilada. Você nãodeve implantá-lo com uma aplicação web.

vaadin-client-compiler-7.x.x.jarO Vaadin Client Compiler é um compilador Java-para-JavaScript que permite construirmódulos de lado cliente, tal como a engine de lado cliente (conjunto de widgets),necessária para aplicações de lado servidor. O compilador é necessário, por exemplo,para compilar componentes add-on para o conjunto de widgets do aplicativo, conformedescrito em Capítulo 17, Using Vaadin Add-ons. Para informações detalhadas sobreo compilador, consulte Secção 13.4, “Compiling a Client-Side Module”. Note que vocênão deve implantar esta biblioteca com a aplicação web.

vaadin-client-compiled-7.x.x.jarUma engine de lado cliente Vaadin pré-compilada (widget set) que inclui todos oswidgets básicos embutidos no Vaadin. Esta biblioteca não é necessária se vocêcompilar o widget set da aplicação com o Vaadin Client Compiler.

vaadin-themes-7.x.x.jarVaadin disponibiliza temas tanto em arquivos SCSS quanto em CSS pré-compilados.A biblioteca é exigida tanto para o uso básico de temas CSS quanto para compilaçãode temas personalizados Sass.

vaadin-theme-compiler7.x.x.jarO Vaadin Theme Compiler compila temas SASS para CSS, como descrito emSecção 8.3, “Syntactically Awesome Stylesheets (Sass)”. Ele requer que as bibliotecasvaadin-themes-7.x.x.jar, que contém os arquivos-fonte SCSS para os temasinternos. A biblioteca precisa ser incluída na implantação no modo de desenvolvimentopara permitir a compilação on-the-fly de temas, mas não é necessária naimplementação de produção, quando os temas são compilados antes da implantação.

Algumas das bibliotecas dependem umas das outras, bem como de bibliotecas disponibilizadasna pasta lib do pacote de instalação, especialmente a lib/vaadin-shared-deps.jar.

As diferentes formas de instalar as bibliotecas são descritas nas seções seguintes.

Note que os JARs vaadin-client-compiler e vaadin-client não devem ser implantadoscom a aplicação web, incluindo-os em WEB-INF/lib. Algumas outras bibliotecas, como vaadin-theme-compiler, não são necessárias na implantação de produção.

2.4. Instalando o Plugin Vaadin para Eclipse

Se você estiver usando o IDE Eclipse, o Plugin Vaadin para Eclipse ajuda muito. Observe quevocê também pode criar projetos Vaadin como projetos Maven no Eclipse.

37Instalando o Plugin Vaadin para Eclipse

Começando com Vaadin

Page 40: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O plugin inclui:

• Assistentes para a criação de novos projetos baseados em Vaadin, temas e widgetsdo lado cliente e os conjuntos de widget.

• Um editor visual para criação de componentes de interface de usuário compostos deuma forma WYSIWYG (O que você vê é o que você obtém). Com o apoio completo apartir do código-fonte para o modelo visual e vice versa, o editor se integra perfeitamentecom o seu processo de desenvolvimento.

2.4.1. Instalando o Plugin IvyDE

O plugin Vaadin para Eclipse requer o plugin Apache IvyDE, que precisa ser instaladomanualmente no Eclipse antes do plugin Vaadin.

1. Selecione Help   Install New Software....

2. Adicione o site de atualização IvyDE clicando no botão Add....

Digite um nome como "Site de Update do Apache Ivy" e a URL do site de atualização:

http://www.apache.org/dist/ant/ivyde/updatesite

. Em seguida, clique em OK. O site Vaadin agora deve aparecer na janela AvailableSoftware.

3. Selecione o novo "Site de Update Apache Ivy" da lista Work with.

4. Selecione os plugins Apache Ivy, Apache Ivy Ant Tasks e Apache IvyDE.

Instalando o Plugin IvyDE38

Começando com Vaadin

Page 41: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O Apache IvyDE Resolve Visualizer é opcional, e requer plugins de dependênciaadicionais a serem instalados.

Então, clique em Next.

5. Revise os detalhes da instalação e clique em Next.

6. Aceite ou não a licença. Por fim, clique em Finish.

7. O Eclipse pode alertar sobre o conteúdo não assinado. Se você se sentir seguro, cliqueem OK.

8. Depois que o plugin for instalado, o Eclipse vai pedir para reiniciar. Você pode instalaro plugin Vaadin antes do reinício, conforme descrito na próxima seção, e responderApply Changes Now.

2.4.2. Instalando o Plugin Vaadin

Você pode instalar o plugin como segue:

1. Selecione Help   Install New Software....

2. Adicione o site de atualização do plugin Vaadin clicando no botão Add....

Digite um nome como "Vaadin Update Site" e a URL do site de atualização:http://vaadin.com/eclipse. Se você quiser ou precisar usar a última versão doplugin instável, o que geralmente é mais compatível com o desenvolvimento e versõesbeta do Vaadin, você pode usar http://vaadin.com/eclipse/experimental edar um nome distintivo como "Vaadin Experimental Site". Em seguida, clique em OK.O site do Vaadin agora deve aparecer na janela Available Software.

3. Atualmente, se estiver usando o plugin estável, a opção Group items by categorydeve ser ativada. Se estiver usando o plugin experimental, deve ser desativada. Issopode mudar no futuro.

4. Selecione todos os plugins Vaadin na árvore.

39Instalando o Plugin Vaadin

Começando com Vaadin

Page 42: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Então, clique em Next.

5. Revise os detalhes da instalação e clique em Next.

6. Aceite ou não a licença. Por fim, clique em Finish.

7. Depois que o plugin for instalado, o Eclipse vai pedir para reiniciar. Clique em Restart.

Se você usar o editor visual, o Eclipse deve ter o navegador interno ativado. A maioria dossistemas operacionais incluem um mecanismo de navegação adequado. Senão, você podeprecisar instalar um, como descrito em Capítulo 7, Visual User Interface Design with Eclipse.

Mais instruções de instalação do plugin do Eclipse podem ser encontradas emhttp://vaadin.com/eclipse.

2.4.3. Atualizando os Plugins

Se você habilitar as atualizações automáticas no Eclipse (veja Window   Preferences  Install/Update   Automatic Updates), o plugin Vaadin será atualizado automaticamente,juntamente com outros plugins. Caso contrário, você pode atualizar o plugin Vaadin manualmenteda seguinte forma:

1. Selecione Help   Check for Updates. O Eclipse entrará em contato com os sites deatualização do software instalado.

2. Depois que as atualizações forem instaladas, o Eclipse vai pedir para reiniciar. Cliqueem Restart.

Observe que atualizar o plugin Vaadin, atualiza apenas o plugin e não as bibliotecas Vaadin,que são específicas do projeto. Veja abaixo as instruções para atualizar as bibliotecas.

Atualizando os Plugins40

Começando com Vaadin

Page 43: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

2.4.4. Atualizando as bibliotecas Vaadin

Atualizar o plugin Vaadin não atualiza as bibliotecas Vaadin. As bibliotecas são específicas dosprojetos. Já que uma versão diferente pode ser utilizada em cada um deles, é necessário atualizá-las separadamente para cada projeto.

1. Abra o ivy.xml em um editor Eclipse.

2. Edite a definição no início do arquivo para configurar a versão do Vaadin.

<!ENTITY vaadin.version "7.0.1">

Você pode especificar um número de versão fixo, como mostrado no exemplo acima,ou uma tag revisão dinâmica como latest.release. Você pode encontrar maisinformações sobre as declarações de dependência na documentação do Ivy.

3. Clique no projeto com o botão direito do mouse e selecione Ivy   Resolve.

Atualizar as bibliotecas pode levar vários minutos. Você pode ver o progresso na barrade status do Eclipse. Você pode obter mais detalhes sobre o progresso clicando noindicador.

4. Se você compilou o conjunto de widgets para o seu projeto, recompile-o clicando nobotão Compile Vaadin widgets na barra de ferramentas do Eclipse.

5. Pare o Tomcat integrado (ou outro servidor) no Eclipse, limpe seus caches, clicandocom o botão direito no servidor e selecionando Clean e Clean Tomcat Work Directory,e o reinicie.

Se você tiver problemas após a atualização das bibliotecas, você pode tentar limpar os cachesdo Ivy clicando com o botão direito no projeto e selecionando Ivy   Clean all caches. Em seguida,clique em Ivy   Resolve novamente.

2.5. Criando e Executando um Projeto com Eclipse

Esta seção fornece instruções sobre como criar um projeto Eclipse novo usando o Plugin Vaadin.A tarefa vai incluir os seguintes passos:

1. Criar um projeto novo

2. Escrever código-fonte

3. Configurar e iniciar o Tomcat (ou algum outro servidor web)

4. Abrir um navegador Web para usar a aplicação

Também mostramos como você pode depurar a aplicação no modo de depuração no Eclipse.

Esta explicação passo a passo presume que você já tenha instalado o Plugin Vaadin para Eclipsee configurado seu ambiente de desenvolvimento, conforme indicado em Secção 2.2, “Configurandoo Ambiente de Desenvolvimento”.

2.5.1. Criando o Projeto

Vamos criar o primeiro projeto de aplicação com as ferramentas instaladas na seção anterior.Primeiro, inicie o Eclipse e siga os seguintes passos:

41Atualizando as bibliotecas Vaadin

Começando com Vaadin

Page 44: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

1. Comece criando um projeto novo, selecionando a partir do menu File   New   Project....

2. Na janela que se abre New Project, selecione Web   Vaadin 7 Project e clique emNext.

Se você optar por Vaadin 6, utilize a versão mais recente deste livro para Vaadin 6 paraobter mais instruções.

3. No passo Vaadin Project, é necessário definir as configurações básicas do projetoweb. Você precisa dar pelo menos o nome do projeto e a configuração de execução.Os valores padrão são suficientes para as outras configurações.

Criando o Projeto42

Começando com Vaadin

Page 45: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Project nameDê um nome ao projeto. O nome deve ser um identificador multi-plataforma válidoutilizável tanto para nome de arquivo quanto para URL. Por isso, é recomendávelusar apenas caracteres alfanuméricos em minúsculas, sublinhados, e sinal demenos.

Use default locationDefina o diretório em que o projeto será criado. O padrão é a pasta do seuworkspace, e você deve deixar assim normalmente. Você pode precisar definir odiretório, por exemplo, se você estiver criando um projeto Eclipse no topo de umaárvore de controle de versão.

Target runtimeDefine o servidor de aplicações que será usado na implamantação. O servidor quevocê instalou, por exemplo, o Apache Tomcat, deve ser selecionadoautomaticamente. Senão, clique em New para configurar um servidor novo noEclipse.

ConfigurationSelecione a configuração para usar. Você normalmente deve usar a configuraçãopadrão para o servidor de aplicações. Se você precisar modificar os facets doprojeto, clique em Modify. A configuração recomendada Servlet 3.0 usa aimplantação @WebServlet, enquanto a Servlet 2.4 usa o velho descritor web.xml.

43Criando o Projeto

Começando com Vaadin

Page 46: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Deployment configurationEsta configuração define o ambiente em que a aplicação será implantada paragerar os arquivos de layout e configuração de diretório do projeto apropriados. Osopções são:

• Servlet (padrão)

• Google App Engine Servlet

• Generic Portlet (Portlet 2.0)

Os passos restantes no assistente dependem da configuração de implantaçãoselecionada; os passos listados nesta seção são para a configuração do servletpadrão. Veja Secção 11.7, “Google App Engine Integration” e Capítulo 12, PortalIntegration para obter instruções sobre o uso de Vaadin nos ambientes alternativos.

Vaadin versionSelecione a versão Vaadin a usar. A lista mostra, por padrão, a última versãodisponível do Vaadin. A seleção inclui compilações nightly SNAPSHOT, se vocêquiser manter-se com as mais recentes últimas versões instáveis.

Você pode alterar a versão mais tarde em ivy.xml.

Você pode clicar em Finish aqui para usar os padrões para o resto das configuraçõesou clicar em Next.

4. As configurações no passo Web Module definem as configurações básicas deimplantação da aplicação web (WAR) e a estrutura do projeto de aplicação web. Todasas configurações são pré-preenchidas, e você normalmente deve aceitá-las como estão.

Context RootA raiz de contexto da aplicação identifica a aplicação na URL usada para acessá-la. Por exemplo, se o projeto tem um contexto myproject e uma única interfacedo usuário na raiz de contexto, a URL seria http://example.com/myproject.O assistente irá sugerir o nome do projeto dado na primeira etapa como o nomede contexto. Você pode alterar a raiz de contexto mais tarde nas propriedades doprojeto no Eclipse.

Content DirectoryO diretório que contém todo o conteúdo a ser incluído na aplicação web (WAR)que é implantada no servidor web. O diretório é relativo ao diretório raiz do projeto.

Você pode simplesmente aceitar os padrões e clicar em Next.

Criando o Projeto44

Começando com Vaadin

Page 47: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5. O passo Vaadin project tem várias configurações de aplicação específicas do Vaadin.Se você está experimentando Vaadin pela primeira vez, você deve não precisar mudarnada. É possível definir a maioria das configurações mais tarde, a não ser a criaçãoda configuração do portlet.

Create project templateFaz o assistente criar um stub de classe UI.

Application NameUm nome para a interface do usuário do aplicativo, exibido na barra de título dajanela do navegador.

Base package nameO nome do pacote Java onde a classe de interface de usuário da aplicação serácolocada.

Application/UI class nameO nome da classe de UI para a aplicação, onde a interface de usuário édesenvolvida.

Portlet versionQuando uma versão de portlet é selecionada (somente Portlet 2.0 é suportado), oassistente irá criar os arquivos necessários para executar a aplicação em um portal.Veja Capítulo 12, Portal Integration para mais informações sobre portlets.

Por fim, clique em Finish para criar o projeto.

2.5.2. Explorando o Projeto

Quando o assistente New Project encerra, ele já fez todo o trabalho para nós: um esqueleto declasse UI foi escrito no diretório src e o WebContent/WEB-INF/web.xml contém um descritorde implantação. A hierarquia do projeto no Project Explorer é mostrada em Figura 2.3, “UmProjeto Vaadin Novo”.

45Explorando o Projeto

Começando com Vaadin

Page 48: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 2.3. Um Projeto Vaadin Novo

As bibliotecas Vaadin e outras dependências são gerenciadas pelo Ivy. Note que as bibliotecasnão são armazenados na pasta do projeto, ainda que elas estejam listadas na pasta virtual JavaResources   Libraries   ivy.xml.

A Classe de UI

A classe de UI criada pelo plugin contém o seguinte código:

package com.example.myproject;import com.vaadin.ui.UI;...@SuppressWarnings("serial")@Theme("myproject")public class MyprojectUI extends UI {@WebServlet(value = "/*", asyncSupported = true)@VaadinServletConfiguration(productionMode = false,ui = MyprojectUI.class)public static class Servlet extends VaadinServlet {}@Overrideprotected void init(VaadinRequest request) {final VerticalLayout layout = new VerticalLayout();layout.setMargin(true);setContent(layout);Button button = new Button("Click Me");button.addClickListener(new Button.ClickListener() {public void buttonClick(ClickEvent event) {layout.addComponent(new Label("Thank you for clicking"));}});layout.addComponent(button);}}

Explorando o Projeto46

Começando com Vaadin

Page 49: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Em um projeto de Servlet 3.0, a implantação é configurada com a classe servlet e uma anotação@WebServlet. O stub inclui a classe servlet como uma classe interna estática. Você podequerer refatorá-lo para uma classe normal separada.

Em um projeto de Servlet 2.3, você teria um descritor de implantação web.xml.

Para um tratamento mais detalhado da implantação, consulte Secção 4.8.4, “Usando um Descritorde Implantação web.xml”.

2.5.3. Dicas de Codificação para Eclipse

Uma das características mais úteis no Eclipse é o auto-complemento de código. PressionandoCtrl+Space no editor, uma lista pop-up com possíveis complementos de nomes de classes emétodos é mostrada, como mostra Figura 2.4, “Auto-complemento de Código Java no Eclipse”,dependendo do contexto da posição do cursor.

Figura 2.4. Auto-complemento de Código Java no Eclipse

Para adicionar uma declaração import de uma classe, como Button, basta pressionarCtrl+Shift+O ou clicar no indicador de erro vermelho no lado esquerdo da janela do editor. Sea classe estiver disponível em vários pacotes, é exibida uma lista de alternativas, como mostradoem Figura 2.5, “Importando Classes Automaticamente”. Para o desenvolvimento do lado servidor,você normalmente deve usar as classes dos pacotes com.vaadin.ui e com.vaadin.server. Vocênão pode usar as classes do lado cliente (sob com.vaadin.client) ou classes do GWT para odesenvolvimento do lado servidor.

Figura 2.5. Importando Classes Automaticamente

47Dicas de Codificação para Eclipse

Começando com Vaadin

Page 50: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

2.5.4. Configurando e Iniciando o Servidor Web

O IDE Eclipse para Desenvolvedores Java EE tem o pacote padrão Web Tools instalado, quesuporta controle de vários servidores web e a implantação automática de conteúdo Web noservidor quando são feitas alterações em um projeto.

Certifique-se de que o Tomcat foi instalado com permissões de usuário. A configuração doservidor web no Eclipse falhará se o usuário não tiver permissões de gravação para os diretóriosde configuração e implantação sob o diretório de instalação do Tomcat.

Siga os seguintes passos.

1. Mude para aba Servers no painel inferior do Eclipse. A lista de servidores deve estarvazia depois de instalar o Eclipse. Clique com o botão direito do mouse na área vaziano painel e selecione New   Server.

2. Selecione Apache   Tomcat v7.0 Server e defina Server's host name comolocalhost, que deve ser o padrão. Se você tiver apenas um Tomcat instalado, Serverruntime só tem uma opção. Clique em Next.

3. Adicione o seu projeto ao servidor, selecionando-o na esquerda e clicando em Addpara adicioná-lo aos projetos configurados à direita. Clique em Finish.

Configurando e Iniciando o Servidor Web48

Começando com Vaadin

Page 51: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

4. O servidor e o projeto agora estão instalados no Eclipse e são mostrados na abaServers. Para iniciar o servidor, clique com o botão direito do mouse no servidor eselecione Debug. Para iniciar o servidor no modo não debug, selecione Start.

5. O servidor se inicia e o diretório WebContent do projeto é publicado no servidor emhttp://localhost:8080/myproject/.

2.5.5. Executando e Depurando

Iniciar sua aplicação é tão fácil quanto selecionar myproject no Project Explorer e, em seguida,Run   Debug As   Debug on Server. O Eclipse então abre o navegador web embutido.

Figura 2.6. Executando uma Aplicação Vaadin

Você pode inserir pontos de interrupção no código Java, clicando duas vezes no lado esquerdoda barra lateral da janela de código-fonte. Por exemplo, se você inserir um ponto de interrupçãono método buttonClick() e clicar no botão What is the time?, o Eclipse vai pedir para mudarpara a perspectiva Debug. A perspectiva Debug irá mostrar onde a execução parou no ponto

49Executando e Depurando

Começando com Vaadin

Page 52: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

de interrupção. Você pode examinar e alterar o estado da aplicação. Para continuar a execução,selecione Resume no menu Run.

Figura 2.7. Depurando uma Aplicação Vaadin

Acima, nós descrevemos como depurar uma aplicação do lado servidor. A depuração deaplicações e widgets do lado cliente é descrita em Secção 13.6, “Debugging Client-Side Code”.

2.6. Usando Vaadin com Maven

Maven é um sistema de gerenciamento de build e dependências comumente utilizado. A bibliotecaprincipal e todos os add-ons do Vaadin estão disponíveis através dele. Você pode usar Mavenno Eclipse, NetBeans ou por linha de comando, conforme descrito nesta seção.

Além do Maven, você pode usar qualquer sistema de gerenciamento de build ou dependênciascompatível com Maven, como Ivy ou Gradle. Para Gradle, consulte Gradle Vaadin Plugin. OPlugin Vaadin para Eclipse usa Ivy para resolver dependências em projetos Vaadin, e devefornecer a configuração básica do Ivy.

2.6.1.Trabalhando a partir de Linha de Comando

Você pode criar um novo projeto Maven com o seguinte comando (dado em uma linha):

$ mvn archetype:generate-DarchetypeGroupId=com.vaadin-DarchetypeArtifactId=vaadin-archetype-application-DarchetypeVersion=7.x.x-DgroupId=your.company-DartifactId=project-name-Dversion=1.0-Dpackaging=war

Os parâmetros são os seguintes:

Usando Vaadin com Maven50

Começando com Vaadin

Page 53: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

archetypeGroupIdO group ID do archetype é com.vaadin para archetypes Vaadin.

archetypeArtifactIdO ID do archetype. Vaadin 7 suporta atualmente o archetype vaadin-archetype-application para aplicações do lado servidor e vaadin-archetype-widgetpara o desenvolvimento de projetos de widgets do lado cliente.

archetypeVersionVersão do archetype. Esta deve ser LATEST para releases Vaadin normais. Para asversões de pré-lançamento, deve ser o número da versão exata, como 7.0.0.beta3.

groupIdUm ID do grupo Maven para o seu projeto. Ele é usado para o nome do pacote Javae normalmente deve ser o seu nome de domínio revertido, comocom.example.myproject. O ID do grupo também é usado para o pacote de código-fonte Java do seu projeto. Por isso, deve ser compatível com Java - apenas caracteresalfanuméricos e underscore.

artifactIdIdentificador do artefato, ou seja, do seu projeto. O identificador pode conter caracteresalfanuméricos, menos, e underscore.

versionNúmero da versão inicial de sua aplicação. O número deve obedecer o formato denumeração de versão Maven.

packagingComo o projeto será empacotado. Normalmente war.

Criar um projeto pode demorar um pouco, já que o Maven baixa todas as suas dependências.A estrutura do projeto criado é mostrada em Figura 2.8, “Um Novo Projeto Vaadin com Maven”.

Figura 2.8. Um Novo Projeto Vaadin com Maven

2.6.2. Compilando e Executando a Aplicação

Antes que a aplicação possa ser instalada, ela deve ser compilada e empacotada como umpacote WAR. Você pode fazer isso com o goal package da seguinte forma:

$ mvn package

51Compilando e Executando a Aplicação

Começando com Vaadin

Page 54: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

A localização do pacote WAR resultante deve ser exibida na saída do comando. Você pode, emseguida, instalá-lo em seu servidor de aplicações favorito.

A forma mais fácil de executar aplicações Vaadin com Maven é usar o servidor web leve Jetty.Depois de compilar o pacote, tudo que você precisa fazer é digitar:

$ mvn jetty:run

O goal especial inicia o servidor Jetty na porta 8080 e instala a aplicação.Você pode, em seguida,abri-lo em um navegador web em http://localhost:8080/project-name.

2.6.3. Utilizando Add-ons e Widget Sets customizados

Se você usar add-ons Vaadin que incluam um widget set ou fizer seus widgets customizados,você precisará habilitar a compilação de widget set no POM. A configuração necessária estádescrita em Secção 17.4, “Using Add-ons in a Maven Project”.

2.7. Criando um projeto no IDE NetBeans

A forma mais fácil de desenvolver uma aplicação Vaadin com o IDE NetBeans é usar o PluginVaadin para NetBeans. Ele permite que você crie novos projetos Vaadin facilmente e oferecemuitos recursos para trabalhar em um projeto. Você pode baixar o plugin emhttp://plugins.netbeans.org/plugin/50531/vaadin-plug-in-for-netbeans. A página de downloadcontém um link para uma visão geral dos recursos do plugin na Wiki NetBeans.

Sem o plugin, você pode bem facilmente criar um projeto Vaadin como um projeto Maven usandoum archetype Vaadin. Você também pode criar um projeto Vaadin como um projeto web normal,mas isso exige muitas etapas manuais para instalar todas as bibliotecas Vaadin, criar a classede interface do usuário, configurar o servlet, criar tema, e assim por diante.

2.7.1. Projeto Maven a partir de um Archetype Vaadin

Ao criar um projeto Maven com um archetype Vaadin, um esqueleto de aplicação é criado comuma classe de UI, tema do projeto e descritor web.xml. A última versão do Vaadin também ébaixada automaticamente.

1. Selecione File   New Project.

2. Selecione Maven   Project from Archetype e clique Next.

3. Encontre vaadin-archetype-application, selecione-o, e clique Next.

4. No passo Nome e Localização, insira o Nome do Projeto. É recomendável utilizarapenas letras minúsculas, da mesma forma como ocorre para nomes de pacotes Javado projeto. Modifique os outros parâmetros para o seu projeto e clique em Finish.

Utilizando Add-ons e Widget Sets customizados52

Começando com Vaadin

Page 55: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 2.9. Adicionando um Novo Projeto Maven no NetBeans

Criar o projeto pode demorar um pouco, já que o Maven carrega todas as dependênciasnecessárias. Uma vez criado, você pode executá-lo, clicando com o botão direito sobre o projetona view Projects e selecionando Run. Na janela Select deployment server aberta, selecioneGlassfish ou Apache Tomcat, e clique OK. Se tudo correr bem, o NetBeans inicia o servidorna porta 8080 e, dependendo da configuração do sistema, abre o navegador padrão paravisualizar a aplicação web. Se não, você pode abri-lo manualmente, por exemplo, emhttp://localhost:8080/myproject. O nome do projeto é utilizado por padrão como ocaminho do contexto da aplicação.

2.8. Criando um projeto com IntelliJ IDEA

A edição Ultimate do IntelliJ IDEA inclui suporte para a criação de aplicações Vaadin, além deexecução e depuração em servidor de aplicações integrado. Com a edição Community, vocêpode criar uma aplicação Vaadin mais facilmente com um archetype Maven e instalá-la em umservidor com uma configuração de execução/depuração Maven.

Para mais informações, consulte o artigo "Creating a simple Web application and deploying it toTomcat" na Enciclopédia wiki do IntelliJ IDEA.

2.8.1. Configurando um Servidor de Aplicações

Para executar a aplicação durante o desenvolvimento na edição Ultimate do IntelliJ IDEA, primeirovocê precisa instalar e configurar um servidor de aplicações que seja integrado com o IDE. Aedição inclui a integração com muitos dos servidores de aplicações mais utilizados.

A seguir, configuramos o Apache Tomcat:

1. Baixe e descompacte o pacote de instalação do Tomcat em um diretório local, conformeindicado em Secção 2.2.3, “Instalando o Apache Tomcat”.

2. Selecione Configure   Settings.

3. Selecione IDE Settings   Application Servers.

4. Selecione +   Tomcat Server para adicionar um servidor Tomcat, ou qualquer outroservidor suportado. Um servidor habilitado para WebSocket, como o Glassfish ouTomEE, é requerido para server push.

53Criando um projeto com IntelliJ IDEA

Começando com Vaadin

Page 56: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5. Na caixa de diálogo Tomcat Server, especifique o diretório home do servidor.

Clique OK.

6. Revise a página de configurações do servidor de aplicações para verificar se ela estáOK.

Então, clique OK.

2.8.2. Criando um Projeto de Aplicação Vaadin Web

Na página de boas-vindas, faça o seguinte:

1. Baixe e descompacte o pacote de instalação Vaadin para uma pasta local, conformeindicado em Secção 2.9, “Pacote de instalação Vaadin”.

2. Selecione New Project

3. Na janela New Project, selecione Java

Criando um Projeto de Aplicação Vaadin Web54

Começando com Vaadin

Page 57: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

4. Digite Nome de Projeto e Localização de Projeto, e selecione o Java SDK que seráusada no projeto. Vaadin requer pelo menos Java 6. Se você não tiver configurado umJava SDK anteriormente, você pode configurá-lo aqui.

Clique Next.

5. Selecione Web Application   Vaadin para adicionar a tecnologia Vaadin ao projeto.

55Criando um Projeto de Aplicação Vaadin Web

Começando com Vaadin

Page 58: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6. Selecione uma versão do Vaadin e um caminho de instalação da distribuição. Vocêprovavelmente também quer um esboço da aplicação, então selecione Create sampleapplication e dê um nome para a classe de UI gerada.

Não clique em Finish ainda.

7. Selecione Application Server na mesma janela. Defina-o como um servidor integradoque você tenha configurado no IntelliJ IDEA, como descrito anteriormente emSecção 2.8.1, “Configurando um Servidor de Aplicações”.

Criando um Projeto de Aplicação Vaadin Web56

Começando com Vaadin

Page 59: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

8. Clique em Finish.

O projeto é criado com o stub de uma classe UI e um descritor de implantação web.xml.

57Criando um Projeto de Aplicação Vaadin Web

Começando com Vaadin

Page 60: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O assistente atualmente não cria uma classe servlet automaticamente, e usa implantaçãocompatível com Servlet 2.4 com um descritor de implantação web.xml.

Implantando o Projeto

Para implantar a aplicação no servidor web integrado, clique com o botão direito do mouse sobreo arquivo index.jsp no projeto e selecione Run 'index.jsp'. Isso inicia o servidor integrado,se ele não estiver rodando ainda, e abre o navegador padrão com a página da aplicação.

2.8.3. Criando um Projeto Maven

Você pode optar por criar um projeto Maven no IntelliJ IDEA. Esta é a forma recomendadaquando utilizando a edição Community. Você não terá a integração do servidor de aplicações,mas poderá implantar a aplicação em um servidor de aplicações utilizando uma configuraçãode execução/ depuração.

1. Selecione New Project

2. Na janela New Project, selecione Maven

3. Digite um nome de projeto, localização, e Java SDK que será usado no projeto. Vaadinrequer pelo menos Java 6. Clique em Next.

4. Dê um GroupID, ArtifactID, e uma Version para o projeto, ou use os valores padrão.

Criando um Projeto Maven58

Começando com Vaadin

Page 61: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5. Marque Create from archetype

6. Se o archetype Vaadin não estiver na lista, clique em Add archetype, digite GroupIdcom.vaadin, ArtifactId vaadin-archetype-application, e Version LATEST (ouum número de versão específico).

Clique em OK na caixa de diálogo.

7. Selecione o com.vaadin:vaadin-archetype-application.

59Criando um Projeto Maven

Começando com Vaadin

Page 62: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Clique Next.

8. Revise as configurações gerais do Maven e definições do projeto novo. Pode sernecessário substituir as configurações, especialmente se você estiver criando um projetoMaven pela primeira vez. Clique em Finish.

Criando um Projeto Maven60

Começando com Vaadin

Page 63: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Criar o projeto Maven leva algum tempo já que o Maven busca as dependências. Uma vez feitoisso, o projeto é criado e o POM Maven é aberto no editor.

Compilando o Projeto

Para compilar uma aplicação Vaadin usando Maven, você pode definir uma configuração deexecução/depuração para executar um objetivo como package para construir o pacote WARimplantável. Ele também irá compilar o conjunto de widgets e tema, se necessário. VejaSecção 2.6.2, “Compilando e Executando a Aplicação” para mais detalhes.

A compilação está inclusa nas instruções a seguir para implantar a aplicação.

Implantando no Servidor

Há plugins Maven para a implantação em vários servidores de aplicações. Por exemplo, paraimplantar no Apache Tomcat, você pode configurar o tomcat-maven-plugin e, em seguida,executar o objetivo tomcat:deploy. Consulte a documentação do plugin que você usa paraobter mais detalhes. Se nenhum plugin Maven existir para um determinado servidor, você semprepode usar algum método de nível inferior para implantar a aplicação, como a execução de umatarefa Ant.

Em seguida, vamos criar uma configuração de execução/depuração para construir, implantar einiciar uma aplicação Maven Vaadin no servidor web leve Jetty.

1. Selecione Run   Edit Configurations.

61Criando um Projeto Maven

Começando com Vaadin

Page 64: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

2. Selecione +   Maven para criar uma nova configuração Maven de execução/depuração.

3. Preencha o campo Name para a configuração de execução. Para a Command line,digite package jetty:run para primeiro compilar e empacotar o projeto e, emseguida, iniciar o Jetty para executá-lo.

Clique OK.

4. Selecione a configuração de execução na barra de ferramentas e clique no botão Runao lado dele.

Compilar o projeto leva algum tempo na primeira vez, já que ele compila o conjunto de widgetse o tema. Uma vez que o console informe que o servidor Jetty foi iniciado, você pode abrir onavegador pela URL padrão http://localhost:8080/.

2.9. Pacote de instalação Vaadin

A forma recomendada de instalar o Vaadin é usar o plugin do Eclipse ou de outros IDEs, ou usarum sistema de gerenciamento de dependências, como o Maven. Entretanto, Vaadin tambémestá disponível como um pacote de distribuição ZIP.

Você pode baixar o pacote de instalação Vaadin mais novo em http://vaadin.com/download/.Por favor, use um utilitário de descompressão ZIP disponível no seu sistema operacional paradescompactar os arquivos do pacote ZIP.

2.9.1. Conteúdo do Pacote

README.TXTEste arquivo Readme fornece instruções simples para instalar o Vaadin em seu projeto.

release-notes.htmlAs notas da release contêm informações sobre os novos recursos da versão, instruçõesde atualização, descrição de compatibilidade, etc. Por favor, abra o arquivo HTMLcom um navegador web.

license.htmlLicença Apache versão 2.0. Por favor, abra o arquivo HTML com um navegador web.

Pacote de instalação Vaadin62

Começando com Vaadin

Page 65: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

pasta libTodas as bibliotecas de dependências exigidas pelo Vaadin estão na pasta lib.

*.jarBibliotecas Vaadin, como descrito em Secção 2.3, “Visão Geral das Bibliotecas Vaadin”.

2.9.2. Instalação de Bibliotecas

Você pode instalar o pacote ZIP Vaadin em alguns passos simples:

1. Copie os arquivos JAR da pasta raiz do pacote para a pasta de bibliotecas web noprojeto WEB-APP/lib. Algumas das bibliotecas são opcionais, como explicado emSecção 2.3, “Visão Geral das Bibliotecas Vaadin”.

2. Também copie os arquivos JAR de dependências da pasta lib para a pasta debibliotecas web do projeto WEB-APP/lib.

A localização da pasta WEB-APP/lib depende da organização do projeto, que depende doambiente de desenvolvimento.

• Em Eclipse Dynamic Web Application projects: WebContent/WEB-INF/lib.

• Em Maven projects: src/main/webapp/WEB-INF/lib.

2.10. Usando Vaadin com Scala

Você pode usar Vaadin com qualquer linguagem compatível com a JVM, como Scala ou Groovy.Porém, há algumas ressalvas quanto a bibliotecas e configuração de projetos. A seguir, damosinstruções para a criação de uma UI em Scala, com o IDE Scala e Plugin Vaadin para Eclipse.

1. Instale o IDE Scala para Eclipse, a partir de um site de atualização Eclipse ou com umadistribuição Eclipse fornecida.

2. Abrir um projeto Vaadin em Java existente ou crie um novo, conforme descrito emSecção 2.5, “Criando e Executando um Projeto com Eclipse”.Você pode excluir a classede UI criada pelo assistente.

3. Alterne para a perspectiva Scala clicando na perspectiva no canto superior direito dajanela do Eclipse.

4. Clique com o botão direito do mouse na pasta do projeto em Project Explorer eselecione Configure   Add Scala Nature.

5. A aplicação web precisa ter scala-library.jar em seu classpath. Se estiver usandoo IDE Scala, você pode copiá-lo de algum lugar sob sua instalação do Eclipse para oclasspath da aplicação web, ou seja, tanto para a pasta WebContent/WEB-INF/libno projeto ou para o caminho da biblioteca do servidor de aplicativos. Se a cópia forde fora do Eclipse para um projeto, atualize o projeto, selecionando-o e pressionandoF5.

Você também pode obtê-lo com uma dependência Ivy ou Maven, apenas certifique-sede que a versão é a mesma que o IDE Scala usa.

Agora você deve ser capaz de criar uma classe de UI em Scala, como segue:

63Instalação de Bibliotecas

Começando com Vaadin

Page 66: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

@Theme("mytheme")class MyScalaUI extends UI {override def init(request: VaadinRequest) = {val content: VerticalLayout = new VerticalLayoutsetContent(content)val label: Label = new Label("Hello, world!")content addComponent label// Lida com a interação do usuáriocontent addComponent new Button("Click Me!",new ClickListener {override def buttonClick(event: ClickEvent) =Notification.show("The time is " + new Date)})}}

O Eclipse e o IDE Scala devem ser capazes de importar as classes Vaadin automaticamentequando você pressionar Ctrl+Shift+O.

Você precisa definir a classe de UI em Scala em uma classe servlet (em projeto Servlet 3.0) ouem um descritor de implantação web.xml, como descrito em Secção 2.5.2, “Explorando oProjeto” para UIs em Java.

O Scaladin add-on permite uma API mais Scala-like para Vaadin. Uma versão compatível Vaadin7 está em desenvolvimento.

Usando Vaadin com Scala64

Começando com Vaadin

Page 67: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 3

Arquitetura

3.1. Visão Geral .............................................................................................. 653.2. Conhecimento Tecnológico ...................................................................... 683.3. Engine de Lado Cliente ........................................................................... 703.4. Eventos e Ouvintes .................................................................................. 71

Na Capítulo 1, Introdução, apresentamos uma breve introdução à arquitetura geral do Vaadin.Este capítulo analisa mais profundamente a arquitetura em um nível mais técnico.

3.1. Visão Geral

Vaadin fornece dois modelos de desenvolvimento de aplicações web: para o lado cliente (onavegador) e para o lado servidor. O modelo de desenvolvimento conduzido pelo servidor é omais poderoso, permitindo o desenvolvimento de aplicações exclusivamente no lado servidor,utilizando uma engine de lado cliente baseada em AJAX que renderiza a interface do usuáriono navegador. O modelo do lado cliente permite o desenvolvimento de widgets e aplicações emJava que são compilados para JavaScript e executados no navegador. Os dois modelos podemcompartilhar seus widgets de UI, temas e código de back-end e serviços, e podem ser misturadosentre si facilmente.

Figura 3.1, “Arquitetura de Execução Vaadin” dá uma ilustração básica da comunicação doslados cliente e servidor, em uma situação de execução em que a página com o código do ladocliente (engine ou aplicação) foi inicialmente carregada no navegador.

O Framework Vaadin consiste em uma API do lado servidor, uma API do lado cliente, um bandode componentes de interface do usuário/widgets em ambos os lados, temas para controlar aaparência, e um modelo de dados que permite a ligação dos componentes do lado servidordiretamente ao dados. Para o desenvolvimento do lado cliente, ele inclui o Compilador Vaadin,que permite compilar Java para JavaScript.

65Book of Vaadin

Page 68: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 3.1. Arquitetura de Execução Vaadin

Um aplicação Vaadin de lado servidor é executada como um servlet, em um servidor web Java,servindo requisições HTTP. O VaadinServlet é normalmente usado como a classe servlet. Oservlet recebe pedidos de clientes e interpretá-os como eventos para uma sessão de usuárioem particular. Os eventos são associados com os componentes da interface do usuário eentregues aos ouvintes de eventos definidos na aplicação. Se a lógica da UI faz alterações nolado servidor dos componentes da interface de usuário, o servlet as renderiza no navegadorweb gerando uma resposta. A engine do lado cliente, que roda no navegador, recebe as respostase as usa para fazer as alterações necessárias na página no navegador.

As principais partes da arquitetura de desenvolvimento orientada por servidor e suas funçõessão as seguintes:

Interface de UsuárioAplicações Vaadin fornecem uma interface de usuário para desenvolvedores fazerema interface entre a lógica de negócios e dados da aplicação. Em nível técnico, a UI éconcebida como uma classe UI que estende com.vaadin.ui.UI. Sua principal tarefaé criar a interface do usuário inicial a partir de componentes de UI e configurar ouvintesde eventos para manipular a entrada do usuário. A UI pode então ser carregada nonavegador utilizando uma URL, ou pode ser incorporada em qualquer página HTML.Para obter informações detalhadas sobre como implementar uma UI, consulteCapítulo 4, Escrevendo uma Aplicação Web de Lado Servidor.

Por favor, note que o termo "UI" é usado ao longo deste livro para se referir tanto aoconceito de interface do usuário em geral, como ao conceito técnico de classe de UI.

Componentes/Widgets de Interface do UsuárioA interface do usuário de uma aplicação Vaadin consiste em componentes que sãocriados e definidos pela aplicação. Cada componente do lado servidor tem umacontraparte do lado cliente, um "widget", com que é renderizado no navegador e comque o usuário interage. Os widgets do lado cliente também podem ser usados poraplicações do lado cliente. Os componentes do lado servidor retransmitem esses

Visão Geral66

Arquitetura

Page 69: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

eventos para a lógica da aplicação. Componentes de campo que têm um valor, queo usuário pode visualizar e editar, podem ser ligados a uma fonte de dados (vejaabaixo). Para uma descrição mais detalhada da arquitetura de componentes deinterface do usuário, consulte Capítulo 5, User Interface Components.

Engine de Lado ClienteA engine do lado cliente do Vaadin gerencia a renderização da UI no navegador web,empregando vários widgets do lado cliente, contrapartes dos componentes do ladoservidor. Ela comunica a interação do usuário para o lado servidor e, em seguida,renderiza as mudanças na UI novamente. A comunicação é feita utilizando requisiçõesde HTTP ou HTTPS assíncronas. Veja Secção 3.3, “Engine de Lado Cliente”.

Servlet VaadinAplicações Vaadin de lado servidor trabalham no topo da API Java Servlet (vejaSecção 3.2.5, “Servlets Java”). O servlet Vaadin, ou mais exatamente a classeVaadinServlet, recebe pedidos de diferentes clientes, determina a que sessão deusuário pertencem, acompanhando as sessões com cookies, e delega as requisiçõespara suas sessões correspondentes. Você pode personalizar o servlet Vaadinestendendo-o.

TemasVaadin faz uma separação entre a aparência e a estrutura de componentes de interfacedo usuário. Enquanto a lógica é tratada como código Java, a apresentação é definidaem themes como CSS ou Sass. Vaadin fornece uma série de temas padrão. Temasdo usuário podem incluir, além de folhas de estilo, templates HTML que definemlayouts customizados e outros recursos como imagens. Os temas são discutidos emdetalhes em Capítulo 8, Themes.

EventosA interação com os componentes de interface do usuário cria eventos, que sãoprocessados primeiro no lado cliente o pelos widgets. Depois, passam todo o caminhoatravés do servidor HTTP, servlet Vaadin, e os componentes de interface de usuárioaté os ouvintes de eventos definidos na aplicação. Veja Secção 3.4, “Eventos eOuvintes”.

Push de ServidorAlém do modelo de programação orientada a eventos, Vaadin suporta push de servidor,onde mudanças na interface do usuário são enviadas diretamente do servidor para ocliente sem uma solicitação do cliente ou um evento. Isso torna possível atualizar UIsimediatamente a partir de outras threads e UIs, sem ter que esperar por um pedido.Veja Secção 11.16, “Server Push”.

Ligação de DadosAlém do modelo de interface do usuário, Vaadin fornece um modelo de dados paradados apresentados em componentes de campo, tais como campos de texto,checkboxes e componentes de seleção, para uma fonte de dados. Usando o modelode dados, os componentes da interface do usuário podem atualizar os dados daaplicação diretamente, muitas vezes sem a necessidade de qualquer código decontrole. Todos os componentes de campo no Vaadin usam esse modelo de dadosinternamente, mas qualquer um deles pode ser ligado a uma fonte de dadosseparadamente também. Por exemplo, você pode ligar um componente Table a umaresposta de consulta SQL. Para uma visão completa do modelo de dados Vaadin,consulte Capítulo 9, Binding Components to Data.

67Visão Geral

Arquitetura

Page 70: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Aplicações de Lado ClienteAlém de aplicações web do lado servidor, Vaadin suporta módulos de aplicações dolado cliente, que rodam no navegador. Módulos do lado cliente podem usar widgets,temas e serviços de back-end como aplicações Vaadin de lado servidor. Eles sãoúteis quando você tem uma necessidade de UI lógica altamente responsiva, comopara jogos ou para servir a um grande número de clientes, com possível código dolado servidor sem estado, e para vários outros fins, como oferecer modo off-line paraaplicações de lado servidor. Por favor, veja Capítulo 14, Client-Side Applications paramais detalhes.

Back-endVaadin é destinado a construção de interfaces de usuário, e é recomendável queoutras camadas da aplicação sejam mantidas separadas da UI. A lógica de negóciospode ser executada no mesmo servlet como o código de UI, geralmente separadospelo menos por uma API Java, possivelmente como EJBs, ou um serviço distribuídopara back-end remoto. O armazenamento de dados é normalmente distribuído paraum sistema de gerenciamento de banco de dados, e normalmente é acessado atravésde uma solução de persistência, como JPA.

3.2. Conhecimento Tecnológico

Esta seção fornece uma introdução às várias tecnologias e projetos em que Vaadin se baseia.Este conhecimento não é necessário para usar Vaadin, mas fornece algum conhecimento casovocê precise fazer extensões de baixo nível no Vaadin.

3.2.1. HTML e JavaScript

A World Wide Web, com todos os seus sites e a maioria das aplicações web, é baseado no usode Linguagem de Marcação de Hipertexto (HTML). HTML define a estrutura e a formatação daspáginas web, e permite a inclusão de gráficos e outros recursos. Baseia-se uma hierarquia deelementos marcados com tags de início e de fim, como <div> ... </div>. Vaadin usaespecificamente XHTML, que é sintaticamente mais rigoroso que o HTML regular. Vaadin usaHTML versão 5, embora de forma conservadora, apoiado pelos principais navegadores e suasversões atualmente mais utilizadas.

JavaScript, por outro lado, é uma linguagem de programação para a incorporação de programasem páginas HTML. Programas JavaScript podem manipular uma página HTML através do Modelode Objeto de Documentos (DOM) da página. Eles também podem manipular eventos de interaçãodo usuário. A engine e os widgets do lado cliente do Vaadin fazem exatamente isso, emborasejam de fato programados em Java, que é compilado para JavaScript com o Vaadin ClientCompiler.

Vaadin esconde em grande parte o uso de HTML, permitindo-lhe concentrar-se na estrutura elógica dos componentes de UI. No desenvolvimento do lado servidor, a UI é desenvolvida emJava utilizando componentes de UI e renderizada pela engine de lado cliente como HTML. Masé possível utilizar templates HTML para definir o layout, bem como formatação HTML em muitoselementos de texto. Além disso, ao desenvolver widgets e UIs do lado cliente, os widgetsembutidos no framework escondem a maior parte da manipulação HTML DOM.

3.2.2. Customizando com CSS e Sass

Enquanto HTML define o conteúdo e a estrutura de uma página web, Cascading Style Sheet(CSS) é uma linguagem para definir o estilo visual, como cores, tamanhos de texto e margens.CSS é baseado em um conjunto de regras que são combinados com a estrutura HTML pelo

Conhecimento Tecnológico68

Arquitetura

Page 71: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

navegador. As propriedades definidas nas regras determinam a aparência visual dos elementosHTML correspondentes.

Sass, ou Syntactically Awesome Stylesheets, é uma extensão da linguagem CSS, que permiteo uso de variáveis, aninhamento, e muitos outros recursos sintáticos que tornam o uso de CSSmais fácil e mais claro. Sass tem dois formatos alternativos, SCSS, que é um superconjunto dasintaxe do CSS3, e uma sintaxe indentada mais antiga, que é mais concisa.

Vaadin manipula estilos com temas definidos com CSS ou Sass, imagens associadas e outrosrecursos. OS Temas do Vaadin são especificamente escritos em SCSS. No modo dedesenvolvimento, arquivos Sass são compilados automaticamente para CSS. Para uso emprodução, você compila os arquivos Sass para CSS com o compilador incluso. O uso de temasestá documentado em detalhes em Capítulo 8, Themes, que também dá uma introdução à CSSe Sass.

3.2.3. AJAX

AJAX, abreviação de Asynchronous JavaScript and XML, é uma técnica para desenvolvimentode aplicações web com interação de usuário responsiva, similar a aplicações desktop tradicionais.Aplicações web convencionais, sejam elas habilitadas para JavaScript ou não, podem obterconteúdo da nova página do servidor apenas carregando nova página. Páginas com AJAXhabilitado, por outro lado, lidam com a interação do usuário em JavaScript, enviam uma solicitaçãopara o servidor de forma assíncrona (sem recarregar a página), recebem conteúdo atualizadona resposta, e modificam a página de acordo com o conteúdo. Dessa forma, apenas pequenaspartes dos dados da página precisam ser carregados. Este objetivo é alcançado pelo uso de umdeterminado conjunto de tecnologias: XHTML, CSS, DOM, JavaScript e a API XMLHttpRequestem JavaScript. XML é apenas uma maneira para serializar dados entre o cliente e o servidor.Em Vaadin, eles são serializados com o JSON mais eficiente.

As solicitações assíncronas utilizadas em AJAX são possibilitadas pela classe XMLHttpRequestem JavaScript. O recurso da API está disponível em todos os principais navegadores e está acaminho de se tornar um padrão W3C.

A comunicação de dados complexos entre o navegador e o servidor requer algum tipo deserialização (ou marshalling) de objetos de dados. O servlet Vaadin e a engine do lado clientelidam com a serialização de objetos de estado compartilhado dos componentes do lado servidorpara os widgets do lado cliente, bem como com a serialização de chamadas RPC entre oswidgets e os componentes do lado servidor.

3.2.4. Google Web Toolkit

O framework Vaadin do lado cliente é baseado no Google Web Toolkit (GWT). Sua finalidade étornar possível desenvolver interfaces de usuário web que rodem no navegador facilmente comJava em vez de JavaScript. Módulos do lado cliente são desenvolvidos com Java e compiladospara JavaScript com o Compilador Vaadin, que é uma extensão do Compilador GWT. O frameworkdo lado cliente também esconde muito da manipulação DOM/HTML e permite que eventos donavegador sejam manipulados Java.

GWT é essencialmente uma tecnologia de lado cliente, normalmente usado para desenvolvera lógica de interface de usuário no navegador web. Módulos puramente de lado cliente aindaprecisam se comunicar com um servidor usando chamadas RPC e pela serialização quaisquerdados. O modo de desenvolvimento orientado a servidor em Vaadin esconde efetivamente todasas comunicações cliente-servidor e permite a manipulação da lógica de interação do usuário emuma aplicação do lado servidor. Isso torna a arquitetura de uma aplicação web baseada em

69AJAX

Arquitetura

Page 72: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

AJAX muito mais simples. No entanto, Vaadin também permite o desenvolvimento de aplicaçõespuramente de lado cliente, conforme descrito em Capítulo 14, Client-Side Applications.

Veja Secção 3.3, “Engine de Lado Cliente” para uma descrição de como o framework do ladocliente baseado em GWT é usado na engine do lado cliente do Vaadin. Capítulo 13, Client-SideVaadin Development fornece informações sobre o desenvolvimento do lado cliente, e Capítulo 16,Integrating with the Server-Side sobre a integração de widgets do lado cliente com oscomponentes do lado servidor.

3.2.5. Servlets Java

Um Servlet Java é uma classe que é executada em um servidor web Java (um contêiner Servlet)para estender as capacidades do servidor. Na prática, é normalmente uma parte de uma aplicaçãoweb, que pode conter páginas HTML para fornecer conteúdo estático; JavaServer Pages (JSP)e Servlets Java para conteúdo dinâmico. Isto é ilustrado em Figura 3.2, “Aplicações Java Webe Servlets”.

Aplicações Web são geralmente empacotadas e implantadas em um servidor como arquivosWAR (Web application ARchive), que são pacotes de JARs Java, compactados em um ZIP. Aaplicação web é definida em um descritor de implantação WEB-INF/web.xml, que define asclasses de servlets e os mapeamentos de caminhos de requisição de URL para os servlets. Istoé descrito em mais detalhes em Secção 4.8.4, “Usando um Descritor de Implantação web.xml”.O classpath para os servlets e suas dependências inclui as pastas WEB-INF/classes e WEB-INF/lib. WEB-INF é uma pasta oculta especial que não pode ser acessada por seu caminhoURL.

Os servlets são classes Java que lidam com requisições HTTP passadas para eles pelo servidoratravés do Java Servlet API. Eles podem gerar HTML, ou outros conteúdos, como resposta.Páginas JSP, por outro lado, são páginas HTML que permitem código-fonte Java embutido. Elassão de fato traduzidas para arquivos de código Java pelo contêiner e, em seguida, compiladaspara servlets.

As UIs de aplicações Vaadin de lado servidor são executados como servlets. Elas são colocadasdentro de uma classe de servlet VaadinServlet, que lida com o rastreamento de sessões eoutras tarefas. Na requisição inicial, ela retorna uma página para carregar HTML e então, emsua maioria, respostas JSON para sincronizar os widgets e suas contra partes do lado servidor.Ela também serve para vários recursos, tais como temas. As UIs do lado servidor sãoimplementadas como classes que estendem a classe UI, conforme descrito em Capítulo 4,Escrevendo uma Aplicação Web de Lado Servidor. A classe é dada como parâmetro para oServlet Vaadin no descritor de implantação web.xml.

A engine de lado cliente do Vaadin, bem como aplicações Vaadin de lado cliente são carregadasno navegador como arquivos JavaScript estáticos. A engine do lado cliente, ou conjunto dewidgets (widget set) em termos técnicos, precisa ser localizada sob VAADIN/widgetsets nocaminho da aplicação web. O conjunto de widgets padrão pré-compilado é servido a partir doJAR vaadin-client-compiled pelo Servlet Vaadin.

3.3. Engine de Lado Cliente

A interface de usuário de uma aplicação Vaadin de lado servidor é renderizada no navegadorpela engine de lado cliente Vaadin. Ela é carregada no navegador quando a página com a UIVaadin é aberta. Os componentes de UI de lado servidor são renderizados usando widgets(como são chamados no Google Web Toolkit) no lado cliente. A engine do lado cliente é ilustradaem Figura 3.3, “Engine de Lado Cliente Vaadin”.

Servlets Java70

Arquitetura

Page 73: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 3.2. Aplicações Java Web e Servlets

Figura 3.3. Engine de Lado Cliente Vaadin

O framework do lado cliente inclui dois tipos de widgets: do GWT e específicos do Vaadin. Asduas coleções de widgets têm sobreposição significativa, onde widgets Vaadin fornecemfuncionalidades um pouco diferentes dos widgets do GWT. Além disso, há muitos widgets add-ons e suas contrapartes de lado servidor, e você pode facilmente baixá-los e instalá-los, conformedescrito em Capítulo 17, Using Vaadin Add-ons. Você também pode desenvolver seus próprioswidgets, conforme descrito em Capítulo 13, Client-Side Vaadin Development.

A renderização de widgets e a comunicação com o lado servidor são tratados emApplicationConnection. A conexão de widgets com suas contrapartes do lado servidor é feitaem conectores, e há um para cada widget que tem um correspondente do lado servidor. Oframework manipula a serialização de estado de componentes de forma transparente, e incluium mecanismo RPC entre os dois lados. A integração de widgets com seus correspondentesdo lado servidor é descrita em Capítulo 16, Integrating with the Server-Side.

3.4. Eventos e Ouvintes

Vaadin oferece um modelo de programação orientada a eventos para lidar com a interação dousuário. Quando um usuário faz alguma coisa na interface, como clicar em um botão ou selecionar

71Eventos e Ouvintes

Arquitetura

Page 74: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

um item, a aplicação precisa saber sobre isso. Muitos frameworks de interface de usuário emJava seguem o padrão Evento-Ouvinte (também conhecido como o padrão de projeto Observer)para comunicar a entrada do usuário para a lógica da aplicação. O mesmo acontece com Vaadin.O padrão de projeto envolve dois tipos de elementos: um objeto que gera ("atira" ou "emite")eventos e um número de ouvintes que escutam os eventos. Quando tal evento ocorre, o objetoenvia uma notificação sobre isso a todos os ouvintes. Num caso típico, existe apenas um ouvinte.

Eventos podem servir para vários propósitos. No Vaadin, o objetivo usual de eventos é lidar coma interação do usuário na interface. O gerenciamento de sessões pode exigir eventos especiais,tais como o time-out, caso em que o evento é, de fato, a falta de interação do usuário. Time-outé um caso especial de evento de tempo ou agendado, onde um evento ocorre em data e horaespecíficos ou quando um determinado tempo já passou.

Para receber eventos de um determinado tipo, uma aplicação deve registrar um objeto ouvintena origem do evento. Os ouvintes (listeners) são registrados nos componentes com um métodoadd*Listener() (com um nome de método específico para o ouvinte).

A maioria dos componentes que tem eventos relacionados definem suas próprias classes deevento e ouvintes correspondentes. Por exemplo, Button tem eventos Button.ClickEvent, quepodem ser ouvidos através da interface Button.ClickListener.

A seguir, manipulamos cliques de botão com um ouvinte implementado como classe anônima:

final Button button = new Button("Push it!");button.addClickListener(new Button.ClickListener() {public void buttonClick(ClickEvent event) {button.setCaption("You pushed it!");}});

Figura 3.4, “Diagrama de Classe de um Ouvinte de Clique de Botão” ilustra o caso em que umaclasse específica da aplicação herda da interface Button.ClickListener para ser capaz de ouviros eventos de clique de botão. A aplicação deve instanciar a classe ouvinte e registrá-la comaddClickListener(). Pode ser uma classe anônima, como descrito acima. Quando umevento ocorre, um objeto do evento é instanciado, neste caso, um Button.ClickEvent. O objetodo evento conhece o componente de UI relacionado, neste caso o Button.

Eventos e Ouvintes72

Arquitetura

Page 75: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 3.4. Diagrama de Classe de um Ouvinte de Clique de Botão

Nos tempos de programação em C, as funções de callback preenchiam em grande parte amesma necessidade que os ouvintes agora. Em linguagens orientadas a objetos, usualmentetemos apenas classes e métodos, e não funções. Logo, as aplicações precisam dar uma interfaceem vez de um ponteiro de função de callback para o framework.

Secção 4.3, “Manipulando Eventos com Ouvintes” entra em detalhes da manipulação de eventosna prática.

73Eventos e Ouvintes

Arquitetura

Page 76: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

74

Page 77: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Parte II. Server-Side FrameworkOf the two sides of Vaadin, the server-side code runs in a Java web server as a servlet, or a portlet in aportal. It offers a server-side API with dozens of user interface components for developing user interfaces,and employs a client-side engine to render them in the browser. User interaction is communicatedtransparently to the server-side application. The user interface can be styled with themes, and bound todata through the Vaadin Data Model.

Page 78: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br
Page 79: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 4

Escrevendo umaAplicação Web de

Lado Servidor

4.1. Visão Geral .............................................................................................. 774.2. Construindo a UI ...................................................................................... 804.3. Manipulando Eventos com Ouvintes ....................................................... 844.4. Imagens e Outros Recursos .................................................................... 864.5. Manipulando Erros .................................................................................. 894.6. Notificações ............................................................................................. 924.7. Ciclo de Vida da Aplicação ...................................................................... 954.8. Implantando uma Aplicação .................................................................. 100

Este capítulo apresenta os fundamentos de desenvolvimento de aplicações web de lado servidorcom Vaadin, concentrando-se nos elementos básicos de uma aplicação a partir de um ponto devista prático.

4.1. Visão Geral

Uma aplicação Vaadin de lado servidor roda como um Servlet Java em um contêiner de servlets.A API Java Servlet está, no entanto, escondida por trás do framework. A interface do usuário

77Book of Vaadin

Page 80: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

da aplicação é implementada como um classe UI, que precisa criar e gerenciar os componentesde interface do usuário que compõem a interface. A entrada do usuário é tratada por ouvintesde eventos. Também é possível vincular os componentes de interface do usuário diretamenteaos dados. O estilo visual da aplicação é definido com temas em arquivos CSS e SCSS. Ícones,outras imagens e arquivos para download são tratadas como recursos, que podem ser externos,servidos pelo servidor de aplicações ou pela própria aplicação.

Figura 4.1. Arquitetura de Aplicação de Lado Servidor

Figura 4.1, “Arquitetura de Aplicação de Lado Servidor” ilustra a arquitetura básica de umaaplicação feita com o Framework Vaadin, com todos os elementos principais, que são introduzidosa seguir e discutidos em detalhes neste capítulo.

Em primeiro lugar, uma aplicação Vaadin deve ter uma ou mais classes de UI que estendam aclasse abstrata com.vaadin.ui.UI e implementem o método init(). Um tema customizadopode ser definido para a UI com uma anotação.

@Theme("hellotheme")public class HelloWorld extends UI {protected void init(VaadinRequest request) {... código de inicialização vai aqui ...}}

Uma UI é uma janela de exibição para uma aplicação Vaadin rodando em uma página web. Umapágina web pode ter várias UIs dentro dela. Tal situação é típica especialmente com portlets emum portal. Uma aplicação pode rodar em várias janelas do navegador, cada uma com umainstância de UI distinta. As UIs de uma aplicação podem ser da mesma classe de UI ou declasses diferentes.

Visão Geral78

Escrevendo uma Aplicação Web de Lado Servidor

Page 81: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O framework Vaadin lida com requisições de servlet internamente e associa as requisições comsessões de usuário e um estado de UI. Devido a isso, você pode desenvolver aplicações Vaadinda forma como você desenvolve aplicações desktop.

A tarefa mais importante na inicialização é a criação da interface do usuário inicial. Isso, e aimplantação de uma UI como um Servlet Java no conteiner de Servlets, conforme descrito emSecção 4.8, “Implantando uma Aplicação”, são os requisitos mínimos para uma aplicação.

Segue abaixo uma breve visão geral dos outros elementos básicos de uma aplicação, além daUI:

UIUma UI representa um fragmento de HTML onde uma aplicação Vaadin é executadaem uma página web. Ela normalmente preenche toda a página, mas também podepreencher apenas uma parte. Você normalmente desenvolve uma aplicação Vaadinestendendo a classe UI e adicionando conteúdo. A UI é essencialmente uma janelade visualização conectada a uma sessão do usuário de uma aplicação, e você podeter muitas dessas visualizações, especialmente em uma aplicação multi-janela.Normalmente, quando o usuário abre uma nova página com a URL da UI Vaadin,uma nova UI (e o objeto Page associado) é criada automaticamente para ela. Todascompartilham a mesma sessão do usuário.

O objeto UI atual pode ser acessado globalmente com UI.getCurrent(). O métodoestático retorna a instância de UI da thread-local para a requisição processada nomomento (veja Secção 11.15.3, “ThreadLocal Pattern”).

PáginaUma UI é associada a um objeto Page, que representa a página web, bem como àjanela do navegador em que a UI roda.

O objeto Page para a requisição processada no momento pode ser acessadoglobalmente a partir de uma aplicação Vaadin com Page.getCurrent(). Isto éequivalente a chamar UI.getCurrent().getPage().

Sessão VaadinUm objeto VaadinSession representa uma sessão de usuário com uma ou maisinterfaces abertas na aplicação. Uma sessão começa quando um usuário abre pelaprimeira vez uma UI de uma aplicação Vaadin, e encerra quando a sessão expira noservidor ou quando ela é encerrada explicitamente.

Componentes de Interface do UsuárioA interface do usuário consiste em componentes que são criados pela aplicação. Elessão definidos hierarquicamente utilizando componentes de layout especiais, com umlayout raiz de conteúdo no topo da hierarquia. A interação do usuário com oscomponentes provoca eventos, relacionados com o componente, que a aplicaçãopode manipular. Componentes de campo destinam-se à introdução de valores epodem ser diretamente ligados a dados usando o modelo de dados do Vaadin. Vocêpode fazer seus próprios componentes de interface do usuário através de herançaou composição. Para uma referência completa de componentes de interface do usuário,consulteCapítulo 5, User Interface Components, para componentes de layout, vejaCapítulo 6, Managing Layout, e para a composição de componentes, consulteSecção 5.24, “Component Composition with CustomComponent”.

79Visão Geral

Escrevendo uma Aplicação Web de Lado Servidor

Page 82: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Eventos e OuvintesVaadin segue um paradigma de programação orientada a eventos, em que eventose ouvintes que lidam com os eventos são a base da manipulação da interação dousuário em uma aplicação (embora push de servidor também seja possível, conformedescrito em Secção 11.16, “Server Push”). Secção 3.4, “Eventos e Ouvintes” dá umaintrodução aos eventos e ouvintes do ponto de vista da arquitetura, enquantoSecção 4.3, “Manipulando Eventos com Ouvintes” tem uma visão mais prática maisadiante neste capítulo.

RecursosA interface do usuário pode exibir imagens e ter links para páginas web ou documentospara download. Estes são tratados como recursos, que podem ser externos, fornecidospelo servidor web, ou da próprio aplicação. Secção 4.4, “Imagens e Outros Recursos”dá uma visão prática dos diferentes tipos de recursos.

TemasA apresentação e a lógica da interface do usuário são separadas. Enquanto a lógicada interface do usuário é tratada como código Java, a apresentação é definida emtemas themes como CSS ou SCSS. Vaadin inclui alguns temas internos. Temasdefinidos pelo usuário podem, além de folhas de estilo, incluir templates HTML quedefinem layouts customizados e outros recursos de temas, tais como imagens. Ostemas são discutidos em detalhes em Capítulo 8, Themes, layouts customizados emSecção 6.14, “Custom Layouts” e recursos de temas em Secção 4.4.4, “Recursos deTema”.

Ligação de DadosComponentes de campo são essencialmente visualizadores de dados, representadosno Modelo de Dados Vaadin. Usando o modelo de dados, os componentes podemobter os seus valores de entrada do usuário e atualizar o modelo de dados diretamente,sem a necessidade de qualquer código de controle. Um componente de campo ésempre vinculado a uma propriedade e um grupo de campos a um item que mantémas propriedades. Os itens podem ser colocados em um contêiner, que pode atuarcomo uma fonte de dados para alguns componentes, tais como tabelas ou listas.Como todos os componentes têm um modelo de dados padrão, eles podem ser ligadosa uma fonte de dados definida pelo usuário. Por exemplo, você pode vincular umcomponente Table a uma resposta de consulta SQL. Para uma visão geral da ligaçãode dados em Vaadin, consulte Capítulo 9, Binding Components to Data.

4.2. Construindo a UI

Interfaces de usuário Vaadin são hierarquicamente construídas a partir de componentes, demodo que os componentes das folhas estão contidos em componentes de layout e em outroscomponentes de contêiner. Construir a hierarquia começa a partir do topo (ou fundo - qualquerque seja o jeito que você gosta de pensar sobre isso), a partir da classe de UI da aplicação.Você normalmente define um componente de layout como o conteúdo da UI e o preenche comoutros componentes.

public class MyHierarchicalUI extends UI {@Overrideprotected void init(VaadinRequest request) {// A raiz da hierarquia de componentesVerticalLayout content = new VerticalLayout();content.setSizeFull(); // Use a janela inteirasetContent(content); // Atache à UI// Adiciona algum componente

Construindo a UI80

Escrevendo uma Aplicação Web de Lado Servidor

Page 83: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

content.addComponent(new Label("Hello!"));// Layout dentro de layoutHorizontalLayout hor = new HorizontalLayout();hor.setSizeFull(); // Use todo o espaço disponível// Alguns componentes dispostos horizontalmenteTree tree = new Tree("My Tree",TreeExample.createTreeContent());hor.addComponent(tree);Table table = new Table("My Table",TableExample.generateContent());table.setSizeFull();hor.addComponent(table);hor.setExpandRatio(table, 1); // Expanda para preenchercontent.addComponent(hor);content.setExpandRatio(hor, 1); // Expanda para preencher}}

A hierarquia de componentes pode ser ilustrada com uma árvore, como se segue:

UI`-- VerticalLayout|-- Label`-- HorizontalLayout|-- Tree`-- Table

O resultado é apresentado em Figura 4.2, “UI de Hierarquia Simples”.

Figura 4.2. UI de Hierarquia Simples

Os componentes internos estão descritos em Capítulo 5, User Interface Components, e os delayout em Capítulo 6, Managing Layout.

O aplicação descrita acima é apenas um exemplo, nada faz. A interação do usuário é tratadacom ouvintes de eventos, conforme descrito um pouco mais tarde em Secção 4.3, “ManipulandoEventos com Ouvintes”.

4.2.1. Arquitetura da Aplicação

Uma vez que sua aplicação cresce além de uma dúzia de linhas, que normalmente ocorre bemdepressa, você precisa começar a pensar na arquitetura da aplicação mais de perto. Você élivre para utilizar todas as técnicas de orientação a objetos em Java disponíveis para organizarseu código em métodos, classes, pacotes e bibliotecas. Uma arquitetura define como estes

81Arquitetura da Aplicação

Escrevendo uma Aplicação Web de Lado Servidor

Page 84: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

módulos se comunicam juntos e que tipo de dependências eles têm entre eles. Ela tambémdefine o escopo de aplicação. O escopo deste livro, no entanto, apenas dá uma oportunidadede mencionar alguns dos padrões de arquitetura mais comuns em aplicações Vaadin.

As seções seguintes descrevem alguns padrões de aplicações básicos. Para mais informaçõessobre arquiteturas comuns, consulte Secção 11.10, “Advanced Application Architectures”, quediscute as arquiteturas em camadas, o padrão Model-View-Presenter (MVP), e assim por diante.Secção 11.15, “Accessing Session-Global Data” discute o problema de passagem essencial dereferências globais, um problema comum, que também é visitado em Secção 4.2.4, “AcessandoUI, Page, Session, e Service”.

4.2.2. Compondo Componentes

Interfaces de usuário tipicamente contêm muitos componentes em uma hierarquia de layouts.Vaadin fornece muitos componentes de layout para dispor componentes na vertical, na horizontal,em um grid, e de muitas outras formas. Você pode estender componentes de layout para criarcomponentes compostos.

class MyView extends VerticalLayout {TextField entry = new TextField("Enter this");Label display = new Label("See this");Button click = new Button("Click This");public MyView() {addComponent(entry);addComponent(display);addComponent(click);// Configure-o um poucosetSizeFull();addStyleName("myview");}}// Use-oLayout myview = new MyView();

Esse padrão de composição é especialmente suportado para a criação de formulários, conformedescrito em Secção 9.4.3, “Binding Member Fields”.

Estender layouts é uma forma fácil de compor de componentes, e é uma boa prática paraencapsular os detalhes de implementação, tais como o componente de layout exato utilizado.Do contrário, os usuários de um determinado componente composto poderiam começar a confiarem tais detalhes de implementação, o que tornaria as mudanças mais difíceis. Para este propósito,Vaadin tem um wrapper especial CustomComponent, que esconde a representação do conteúdo.

class MyView extends CustomComponent {TextField entry = new TextField("Enter this");Label display = new Label("See this");Button click = new Button("Click This");public MyView() {Layout layout = new VerticalLayout();layout.addComponent(entry);layout.addComponent(display);layout.addComponent(click);setCompositionRoot(layout);setSizeFull();}}

Compondo Componentes82

Escrevendo uma Aplicação Web de Lado Servidor

Page 85: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Use-oMyView myview = new MyView();

Para uma descrição mais detalhada do CustomComponent, veja Secção 5.24, “ComponentComposition with CustomComponent”. O Plugin Vaadin para Eclipse também inclui um editorvisual para componentes compostos, conforme descrito em Capítulo 7, Visual User InterfaceDesign with Eclipse.

4.2.3. Navegação de View

Enquanto as aplicações mais simples têm apenas uma única view (ou tela), talvez a maioriatenha muitas. Mesmo com uma única view, muitas vezes você quer ter sub-views, por exemplo,para exibir conteúdo diferente. Figura 4.3, “Navegação Entre Views” ilustra uma navegação típicaentre diferentes views de nível superior de uma aplicação, e uma view principal com sub-views.

Figura 4.3. Navegação Entre Views

O Navigator descrito em Secção 11.9, “Navigating in an Application” é um gerenciador de viewsque fornece uma forma flexível para navegar entre views e sub-views, enquanto gerencia ofragmento URI na URL da página para permitir adicionar páginas aos favoritos, links e históricodo navegador.

Muitas vezes, views de aplicações Vaadin são parte de algo maior. Nesses casos, pode sernecessário integrar as aplicações Vaadin com outro site. Você pode usar as técnicas deincorporação descritas em Secção 11.2, “Embedding UIs in Web Pages”.

4.2.4. Acessando UI, Page, Session, e Service

Você pode obter a UI e a página em que um componente está atachado com getUI() egetPage().

No entanto, os valores são nulos até que o componente esteja atachado à UI e tipicamentenão está quando você precisa deles nos construtores. Portanto, é preferível acessar UI, página,sessão e objetos de serviço, de qualquer lugar da aplicação, usando os métodos estáticosgetCurrent() de suas respetivas classes UI, Page, VaadinSession, e VaadinService.

// Defina um local default para a aplicaçãoUI.getCurrent().setLocale(new Locale("en"));// Defina o título da página (janela ou legenda da aba)Page.getCurrent().setTitle("My Page");

83Navegação de View

Escrevendo uma Aplicação Web de Lado Servidor

Page 86: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Defina um atributo de sessãoVaadinSession.getCurrent().setAttribute("myattrib", "hello");// Acesse os parâmetros de serviço HTTPFile baseDir = VaadinService.getCurrent().getBaseDirectory();

Você também pode obter página e sessão a partir de uma UI com getPage() e getSession().E o service a partir da VaadinSession com getService().

Os métodos estáticos usam o suporte da ThreadLocal embutida. O padrão é descrito emSecção 11.15.3, “ThreadLocal Pattern”.

4.3. Manipulando Eventos com Ouvintes

Vamos colocar em prática o que aprendemos sobre manipulação de eventos em Secção 3.4,“Eventos e Ouvintes”. Você pode implementar interfaces de ouvintes em uma classe regular,mas isso traz o problema de diferenciar entre diferentes fontes de eventos. Usar classes anônimaspara ouvintes é recomendável na maioria dos casos.

4.3.1. Implementando um Ouvinte em uma Classe Regular

O exemplo a seguir segue um padrão típico, onde você tem um componente Button e um ouvinteque lida com a interação do usuário (cliques) comunicada à aplicação com eventos. Aqui vamosdefinir uma classe que escuta clique eventos.

public class MyComposite extends CustomComponentimplements Button.ClickListener {Button button; // Definido aqui para acessopublic MyComposite() {Layout layout = new HorizontalLayout();// Apenas um componente simples em sua composiçãobutton = new Button("Do not push this");button.addClickListener(this);layout.addComponent(button);setCompositionRoot(layout);}// Implementação do método ouvintepublic void buttonClick(ClickEvent event) {button.setCaption("Do not push this again");}}

4.3.2. Diferenciando Fontes de Eventos

Se uma aplicação recebe eventos do mesmo tipo a partir de várias fontes, como vários botões,ela tem que ser capaz de distinguir entre as fontes. Ao usar um ouvinte de classe regular, adistinção entre os componentes pode ser feita comparando a fonte do evento com cada um doscomponentes. O método para identificação da fonte depende do tipo de evento.

public class TheButtons extends CustomComponentimplements Button.ClickListener {Button onebutton;Button toobutton;public TheButtons() {onebutton = new Button("Button One", this);toobutton = new Button("A Button Too", this);// Coloque-os no mesmo layoutLayout root = new HorizontalLayout();

Manipulando Eventos com Ouvintes84

Escrevendo uma Aplicação Web de Lado Servidor

Page 87: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

root.addComponent(onebutton);root.addComponent(toobutton);setCompositionRoot(root);}@Overridepublic void buttonClick(ClickEvent event) {// Diferencie alvos pela fonte do eventoif (event.getButton() == onebutton)onebutton.setCaption ("Pushed one");else if (event.getButton() == toobutton)toobutton.setCaption ("Pushed too");}}

Existem outras técnicas para distinguir fontes de eventos, como o uso de propriedades de objetos,nomes ou legendas. Usar legendas ou qualquer outro texto visível é geralmente desaconselhável,pois pode criar problemas para a internacionalização. Utilizar outras strings como símbolostambém pode ser perigoso, porque a sintaxe de tais strings é verificada apenas em tempo deexecução.

4.3.3. A maneira Mais Fácil: Usando Classes Anônimas

De longe, a forma mais fácil e simples de manipular eventos é utilizar classes locais anônimas.Isso encapsula a manipulação de eventos onde o componente é definido, e não requer gerenciarimplementações de interface. O exemplo a seguir define uma classe anônima que herda dainterface Button.ClickListener.

// Um componente que dispara eventos de cliquefinal Button button = new Button("Click Me!");// Manipula os eventos com uma classe anônimabutton.addClickListener(new Button.ClickListener() {public void buttonClick(ClickEvent event) {button.setCaption("You made me click!");}});

Objetos locais referenciados a partir de uma classe anônima, como o objeto Button no exemploacima, devem ser declarados final.

A maioria dos componentes permitem passar um ouvinte no construtor, removendo assim umaou duas linhas. No entanto, observe que para acessar um objeto a partir de uma classe anônima,você precisa usar uma referência declarada antes da execução do construtor, por exemplo, umavariável membro da classe externa. Se for declarada na mesma expressão onde o construtor échamado, ela ainda não existe. Nesses casos, você precisa obter uma referência para ocomponente a partir do objeto de evento.

final Button button = new Button("Click It!",new Button.ClickListener() {@Overridepublic void buttonClick(ClickEvent event) {event.getButton().setCaption("Done!");}});

85A maneira Mais Fácil: Usando Classes Anônimas

Escrevendo uma Aplicação Web de Lado Servidor

Page 88: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

4.4. Imagens e Outros Recursos

Aplicações Web podem exibir vários recursos, tais como imagens, outro conteúdo incorporado,ou arquivos para download, que o navegador tem que carregar do servidor. Recursos de imagemsão normalmente exibidos com o componente Image ou como ícones de componentes.Animações em Flash pode ser exibidas com Flash, frames embutidos no navegador comBrowserFrame, e outros conteúdos com o componente Embedded, conforme descrito emSecção 5.19, “Embedded Resources”. Arquivos para download geralmente são fornecidos peloclique de um Link.

O servidor web pode fornecer esses recursos de várias formas. Recursos estáticos podem serfornecidos sem ter que requisitá-los a partir da aplicação. Para recursos dinâmicos, a aplicaçãodo usuário deve ser capaz de criá-los dinamicamente. As interfaces de requisição de recursosem Vaadin permitem que as aplicações tanto referenciem recursos estáticos, como os criemdinamicamente. A criação dinâmica inclui as classes StreamResource e RequestHandlerdescritas em Secção 11.4, “Request Handlers”.

Vaadin também oferece facilidades de baixo nível para recuperar a URI e outros parâmetros deuma requisição HTTP. Vamos primeiro ver como as aplicações podem fornecer vários tipos derecursos e, em seguida, ver as interfaces de baixo nível para manipular URIs e parâmetros parafornecer recursos e funcionalidades.

Observe que o uso de manipuladores de requisição para criar "páginas" normalmente não ésignificativo em Vaadin ou em aplicações AJAX em geral. Por favor, veja Secção 3.2.3, “AJAX”para uma explicação detalhada.

4.4.1. Interfaces e Classes de Recursos

As classes de recursos em Vaadin estão agrupadas em duas interfaces: uma genérica Resourcee uma mais específica ConnectorResource para recursos fornecidos pelo servlet.

Figura 4.4. Diagrama de Interfaces e Classes de Recursos

4.4.2. Recursos de Arquivos

Recursos de arquivos são arquivos armazenados em qualquer lugar no sistema de arquivos.Como tal, eles não podem ser recuperadas por uma URL normal do servidor, mas precisam sersolicitados através do servlet Vaadin. O uso de recursos de arquivos normalmente é necessáriopara dados persistentes do usuário que não são empacotados na aplicação web, que nãopersistiriam entre reimplantações.

Um objeto de arquivo que pode ser acessado como um recurso de arquivo é definido com aclasse padrão java.io.File.Você pode criar o arquivo com um caminho absoluto ou relativo, mas

Imagens e Outros Recursos86

Escrevendo uma Aplicação Web de Lado Servidor

Page 89: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

o caminho base do caminho relativo depende da instalação do servidor web. Por exemplo, como Apache Tomcat, o diretório atual padrão seria o caminho de instalação do Tomcat.

No exemplo a seguir, fornecemos um recurso de imagem a partir de um arquivo armazenadona aplicação web. Observe que a imagem é armazenada na pasta WEB-INF, que é uma pastaespecial nunca acessível usando uma URL, ao contrário das outras pastas de uma aplicaçãoweb. Esta é uma solução de segurança - outra forma seria armazenar o recurso em outra partedo sistema de arquivos.

// Encontra o diretório da aplicaçãoString basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();// Imagem como recurso de arquivoFileResource resource = new FileResource(new File(basepath +"/WEB-INF/images/image.png"));// Mostra a imagem na aplicaçãoImage image = new Image("Image from file", resource);// Permite que o usuário veja o arquivo no navegador e baixe-oLink link = new Link("Link to the image file", resource);

O resultado, bem como a estrutura da pasta onde o arquivo está armazenado em um projetoVaadin regular no Eclipse, é mostrado em Figura 4.5, “Recurso de Arquivo”.

Figura 4.5. Recurso de Arquivo

4.4.3. Recursos de Carregamento de Classe

O ClassResource permite que recursos sejam carregados a partir do classpath usando oCarregador de Classes Java. Normalmente, o caminho relevante de classes é a pasta WEB-INF/classes sob a aplicação web, onde a compilação Java deve compilar as classes Java ecopiar outros arquivos da árvore de origem.

O exemplo de uma linha abaixo carrega um recurso de imagem a partir do pacote da aplicaçãoe apresenta-o em um componente Image.

layout.addComponent(new Image(null,new ClassResource("smiley.jpg")));

4.4.4. Recursos de Tema

Recursos de tema da classe ThemeResource são arquivos, tipicamente imagens, inclusos emum tema. Um tema fica localizado no caminho VAADIN/themes/themename em uma aplicaçãoweb. O nome de um recurso de tema é dado como parâmetro para o construtor, com um caminhorelativo à pasta do tema.

// Um recurso de tema no tema atual ("mytheme")// Localizado em: VAADIN/themes/mytheme/img/themeimage.pngThemeResource resource = new ThemeResource("img/themeimage.png");// Usando o recursoImage image = new Image("My Theme Image", resource);

87Recursos de Carregamento de Classe

Escrevendo uma Aplicação Web de Lado Servidor

Page 90: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

O resultado é mostrado em Figura 4.6, “Recursos de Tema”, também ilustrando a estrutura dapasta para o arquivo de recurso do tema em um projeto Eclipse.

Figura 4.6. Recursos de Tema

Para usar os recursos de tema, você deve definir o tema para a UI. Veja Capítulo 8, Themespara mais informações.

4.4.5. Recursos de Stream

Recursos de stream permitem criar conteúdo dinâmico de recursos. Os gráficos são exemplostípicos de imagens dinâmicas. Para definir um recurso de stream, você precisa implementar ainterface StreamResource.StreamSource e seu método getStream(). O método deve retornarum InputStream que possa ser lido.

O exemplo a seguir demonstra a criação de uma imagem simples em formato PNG.

import java.awt.image.*;public class MyImageSourceimplements StreamResource.StreamSource {ByteArrayOutputStream imagebuffer = null;int reloads = 0;/* Precisamos implementar esse método que retorna* o recurso como um stream. */public InputStream getStream () {/* Cria uma imagem e desenha algo nela. */BufferedImage image = new BufferedImage (200, 200,BufferedImage.TYPE_INT_RGB);Graphics drawable = image.getGraphics();drawable.setColor(Color.lightGray);drawable.fillRect(0,0,200,200);drawable.setColor(Color.yellow);drawable.fillOval(25,25,150,150);drawable.setColor(Color.blue);drawable.drawRect(0,0,199,199);drawable.setColor(Color.black);drawable.drawString("Reloads="+reloads, 75, 100);reloads++;try {/* Escreve a imagem no buffer. */imagebuffer = new ByteArrayOutputStream();

Recursos de Stream88

Escrevendo uma Aplicação Web de Lado Servidor

Page 91: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

ImageIO.write(image, "png", imagebuffer);/* Retorna um stream a partir do buffer. */return new ByteArrayInputStream(imagebuffer.toByteArray());} catch (IOException e) {return null;}}}

O conteúdo da imagem gerada é dinâmico, uma vez que atualiza o contador a cada chamada.O método ImageIO.write() escreve a imagem em um stream de saída, enquanto temos queretornar um stream de entrada. Então, armazenamos o conteúdo da imagem em um buffertemporário.

A seguir, mostramos a imagem com componente Image.

// Cria uma instância da nossa fonte de stream.StreamResource.StreamSource imagesource = new MyImageSource ();// Cria um recurso que usa a fonte do stream e dá um nome a ela.// O construtor registrará automaticamente o recurso// na aplicação.StreamResource resource =new StreamResource(imagesource, "myimage.png");// Cria um componente de imagem que pega seu conteúdo// a partir do recurso.layout.addComponent(new Image("Image title", resource));

A imagem resultante é mostrada na Figura 4.7, “Um Recurso de Stream”.

Figura 4.7. Um Recurso de Stream

Outra forma de criar conteúdo dinâmico é com um manipulador de requisições, descrito emSecção 11.4, “Request Handlers”.

4.5. Manipulando Erros

4.5.1. Indicador e Mensagem de Erro

Todos os componentes têm um indicador de erro interno que é ativado se a validação docomponente falhar, e pode ser configurado de forma explícita com setComponentError().Normalmente, o indicador de erro é colocado à direita da legenda do componente. O indicadorde erro é parte da legenda do componente. Logo, sua colocação é geralmente gerenciada pelo

89Manipulando Erros

Escrevendo uma Aplicação Web de Lado Servidor

Page 92: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

layout em que o componente está. Mas alguns componentes o gerenciam por si só. Ao passaro cursor do mouse sobre o campo, a mensagem de erro é exibida.

textfield.setComponentError(new UserError("Bad value"));button.setComponentError(new UserError("Bad click"));

O resultado é mostrado em Figura 4.8, “Indicador de Erro Ativo”.

Figura 4.8. Indicador de Erro Ativo

4.5.2. Customizando Mensagens do Sistema

Mensagens de sistema são notificações que indicam um estado inválido em uma aplicação, quenormalmente requer a reinicialização dela.Timeout de sessão talvez seja o exemplo mais típico.

Mensagens de sistema são strings gerenciadas na classe SystemMessages.

sessionExpiredSessão de servlet da aplicação expirado. A sessão expira se requisições de servidornão são feitas durante o período de timeout da sessão. O timeout de sessão podeser configurado com o parâmetro session-timeout no web.xml, conforme descritoem Secção 4.8.4, “Usando um Descritor de Implantação web.xml”.

communicationErrorUm problema de comunicação não especificado entre a engine Vaadin do lado clientee o servidor de aplicações. O servidor pode estar indisponível ou há algum outroproblema.

authenticationErrorEste erro ocorre se uma resposta 401 (não autorizado) é recebida do servidor parauma requisição.

internalErrorUm problema interno grave, possivelmente indicando um bug na engine Vaadin delado cliente ou em algum código customizado do lado cliente.

outOfSyncO estado do lado cliente é inválido em relação ao estado do lado servidor.

cookiesDisabledInforma ao usuário que os cookies estão desativados no navegador e a aplicação nãofunciona sem eles.

Cada mensagem tem quatro propriedades: uma legenda curta, a mensagem de fato, uma URLpara a qual redirecionar depois de exibir a mensagem, e uma propriedade que indica se anotificação está ativada.

Detalhes adicionais podem ser escritos em Inglês na janela do console de depuração descritoem Secção 11.3, “Debug Mode and Window”.

Customizando Mensagens do Sistema90

Escrevendo uma Aplicação Web de Lado Servidor

Page 93: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Você pode sobrescrever as mensagens de sistema padrão, definindo oSystemMessagesProvider no VaadinService. Você precisa implementar o métodogetSystemMessages(), que deve retornar um objeto SystemMessages. A forma mais fácilde customizar as mensagens é usar um objeto CustomizedSystemMessages.

Você pode definir o provedor de mensagem do sistema no método servletInitialized()de uma classe de servlet customizado, por exemplo, da seguinte forma:

getService().setSystemMessagesProvider(new SystemMessagesProvider() {@Override public SystemMessages getSystemMessages(SystemMessagesInfo systemMessagesInfo) {CustomizedSystemMessages messages =new CustomizedSystemMessages();messages.setCommunicationErrorCaption("Comm Err");messages.setCommunicationErrorMessage("This is bad.");messages.setCommunicationErrorNotificationEnabled(true);messages.setCommunicationErrorURL("http://vaadin.com/");return messages;}});

Veja Secção 4.7.2, “Servlet Vaadin, Portlet, e Serviço” para obter informações sobre acustomização de servlets Vaadin.

4.5.3. Manipulando Exceções Não Tratadas

Manipular eventos pode resultar em exceções na lógica da aplicação ou no próprio framework.Mas algumas delas podem não ser tratadas adequadamente pela aplicação. Nesses casos, elassão eventualmente capturadas pelo framework. Ele delega as exceções para oDefaultErrorHandler, que mostra o exceção como um erro de componente, ou seja, como umpequeno sinal vermelho "!", dependendo do tema. Se o usuário passa o ponteiro do mouse sobreele, toda a stacktrace da exceção é mostrada em uma caixa, como ilustrado em Figura 4.9,“Exceção Não Capturada no Indicador de Erro do Componente”.

Figura 4.9. Exceção Não Capturada no Indicador de Erro do Componente

Você pode personalizar o tratamento padrão de erros através da implementação de umErrorHandler customizado, habilitando-o com setErrorHandler() em qualquer um doscomponentes da hierarquia de componentes, inclusive nos objetos UI e VaadinSession. Vocêtambém pode implementar ErrorHandler ou estender DefaultErrorHandler. No exemplo aseguir, vamos modificar o comportamento do manipulador padrão.

91Manipulando Exceções Não Tratadas

Escrevendo uma Aplicação Web de Lado Servidor

Page 94: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Aqui está um código que produz uma exceção não capturada final VerticalLayout layout = new VerticalLayout();final Button button = new Button("Click Me!",new Button.ClickListener() {public void buttonClick(ClickEvent event) {((String)null).length(); // Null-pointer exception}});layout.addComponent(button);// Configure o manipulador de erro para a interface do usuárioUI.getCurrent().setErrorHandler(new DefaultErrorHandler() {@Overridepublic void error(com.vaadin.server.ErrorEvent event) {// Encontre a causa finalString cause = "<b>The click failed because:</b><br/>";for (Throwable t = event.getThrowable(); t != null;t = t.getCause())if (t.getCause() == null) // We're at final causecause += t.getClass().getName() + "<br/>";// Mostre a mensagem de erro de uma forma personalizadalayout.addComponent(new Label(cause, ContentMode.HTML));// Faça o tratamento de erros padrão (opcional)doDefault(event);} });

O exemplo acima também demonstra como encontrar a causa final na stacktrace.

Ao estender DefaultErrorHandler, você pode chamar doDefault(), como foi feitoanteriormente, para executar o tratamento de erros padrão, como mostrar o erro no componenteonde a exceção foi lançada. Veja o código fonte da aplicação para mais detalhes. Você podechamar findAbstractComponent(event) para encontrar o componente que causou o erro.Se o erro não está associado a um componente, o retorno é nulo.

4.6. Notificações

Notificações são caixas de erro ou informações que aparecem brevemente, geralmente no centroda tela. Uma caixa de notificação tem uma legenda e descrição e ícone opcionais. A caixapermanece na tela por um tempo pré-definido ou até que o usuário clique nela. O tipo danotificação define sua aparência e comportamento padrão.

Há duas formas de criar uma notificação. A mais fácil é usar o método estáticoNotification.show(), que recebe o título da notificação e descrição e tipo de notificaçãoopcionais como parâmetros, e exibe na página atual.

Notification.show("This is the caption","This is the description",Notification.Type.WARNING_MESSAGE);

Para obter mais controle, você pode criar um objeto Notification. Existem diferentes construtoresque recebem apenas a legenda e, opcionalmente, descrição, tipo de notificação e se HTML épermitido ou não. As notificações são mostradas em uma Page, geralmente a página atual.

new Notification("This is a warning","<br/>This is the <i>last</i

Notificações92

Escrevendo uma Aplicação Web de Lado Servidor

Page 95: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 4.10. Notificação

> warning",Notification.TYPE_WARNING_MESSAGE, true).show(Page.getCurrent());

The caption and description are by default written on the same line. If you want to have a linebreak between them, use the XHTML line break markup "<br/>" if HTML is enabled, or "\n" ifnot. HTML is disabled by default, but can be enabled with setHtmlContentAllowed(true).When enabled, you can use any XHTML markup in the caption and description of a notification.If it is in any way possible to get the notification content from user input, you should either disallowHTML or sanitize the content carefully, as noted in Secção 11.8.1, “Sanitizing User Input toPrevent Cross-Site Scripting”.

Figura 4.11. Notificação com Formatação HTML

4.6.1.Tipos de Notificação

O tipo de notificação define o estilo padrão geral e o comportamento de uma notificação. Senenhum tipo de notificação é dado, o tipo "humanized" é usado como padrão. Os tipos denotificação, listados abaixo, são definidos na classe Notification.Type.

TYPE_HUMANIZED_MESSAGEUma mensagem que não incomoda tanto, amigável ao usuário: ela não exigeconfirmação por clique e desaparece rapidamente. É centralizada e tem uma cor cinzaneutra.

TYPE_WARNING_MESSAGEOs avisos são mensagens de média importância. Eles são exibidos com cores quenão são neutras nem distraídas demais. Um alerta é exibido por 1,5 segundos, maso usuário pode clicar na caixa de mensagem para rejeitá-lo. O usuário pode continuarinteragindo com a aplicação enquanto o aviso é exibido.

93Tipos de Notificação

Escrevendo uma Aplicação Web de Lado Servidor

Page 96: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

TYPE_ERROR_MESSAGEAs mensagens de erro são notificações que requerem a maior atenção do usuário,com cores de alerta, e elas exigem que o usuário clique na mensagem para fechá-la.A caixa de mensagem de erro não inclui por si só uma instrução para clicar namensagem, embora o botão fechar no canto superior direito indique visualmente. Aocontrário de outras notificações, o usuário não pode interagir com a aplicação enquantoa mensagem de erro é exibida.

TYPE_TRAY_NOTIFICATIONNotificações de bandeja são exibidas na área de "bandeja do sistema", ou seja, nocanto inferior direito da tela do browser. Como elas não costumam obscurecer ainterface do usuário, elas são exibidas por mais tempo que as mensagens humanizadasou avisos, três segundos por padrão. O usuário pode continuar interagindo com aaplicação normalmente enquanto a notificação da bandeja é exibida.

4.6.2. Customizando Notificações

Todas as características específicas dos tipos de notificação podem ser controladas com aspropriedades de Notification. Uma vez configurada, você precisa mostrá-la na página atual.

// Notificação com configurações padrão para um avisoNotification notif = new Notification("Warning","<br/>Area of reindeer husbandry",Notification.TYPE_WARNING_MESSAGE);// Customize-anotif.setDelayMsec(20000);notif.setPosition(Position.BOTTOM_RIGHT);notif.setStyleName("mystyle");notif.setIcon(new ThemeResource("img/reindeer.png"));// Mostre-a na páginanotif.show(Page.getCurrent());

O método setPosition() permite definir o posicionamento da notificação. A posição podeser especificada por qualquer uma das constantes definidas no enum Position.

O método setDelayMSec() permite definir o tempo por que a notificação é exibida emmilissegundos. O valor do parâmetro -1 significa que a mensagem é exibida até que o usuárioclique na caixa de mensagem. Isso também impede a interação com outras partes da janela daaplicação, que é o comportamento padrão para as notificações de erro. No entanto, isso nãoadiciona o botão fechar que a notificação de erro tem.

4.6.3. Customizando com CSS

.v-Notification {}

.popupContent {}

.gwt-HTML {}h1 {}p {}

Customizando Notificações94

Escrevendo uma Aplicação Web de Lado Servidor

Page 97: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

A caixa de notificação é um elemento div flutuante sob o elemento body da página. Ela temum estilo v-Notification global. O conteúdo é acondicionado dentro de um elemento comestilo popupContent. A legenda está dentro de um elemento h1 e a descrição, de um elementop.

Para customizá-lo, adicione um estilo ao objeto Notification com setStyleName("mystyle"),e faça as configurações no tema, por exemplo, como se segue:

.v-Notification.mystyle {background: #FFFF00;border: 10px solid #C00000;color: black;}

O resultado é mostrado, com o ícone definido anteriormente no exemplo de customização, emFigura 4.12, “Uma Notificação Customizada”.

Figura 4.12. Uma Notificação Customizada

4.7. Ciclo de Vida da Aplicação

Nesta seção, nós olhamos em detalhes mais técnicos a implantação de aplicações, as sessõesdo usuário, e o ciclo de vida da instância de UI. Esses detalhes não são geralmente necessáriospara escrever aplicações Vaadin, mas podem ser úteis para compreender como eles realmentefuncionam e, especialmente, em que circunstâncias a execução deles termina.

4.7.1. Implantação

Antes de uma aplicação Vaadin poder ser usada, ela deve ser implantada em um servidor webJava, conforme descrito em Secção 4.8, “Implantando uma Aplicação”. A implantação lê asclasses servlet com a anotação @WebServlet (Servlet 3.0) ou o descritor de implantaçãoweb.xml (Servlet 2.4) na aplicação para registrar os servlets em uma URL específica e carregaras classes. A implantação normalmente não roda ainda qualquer código da aplicação, emborablocos estáticos em classes sejam executados quando elas são carregadas.

Desimplantação e Reimplantação

As aplicações são desimplantadas quando o servidor é desligado, durante a reimplantação, equando são explicitamente desimplantadas. Desimplantar uma aplicação Vaadin do lado servidortermina a sua execução.Todas as classes da aplicação são descarregados, e o espaço no heapalocado pela aplicação é liberado para o garbage collector.

Se qualquer sessão de usuário estiver aberta neste momento, o estado do lado cliente da UI ésuspenso e um erro de sincronização é exibido na próxima requisição de servidor.

95Ciclo de Vida da Aplicação

Escrevendo uma Aplicação Web de Lado Servidor

Page 98: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Reimplantação e Serialização

Alguns servidores, como o Tomcat, suportam o hot deployment, onde as classes sãorecarregadas, preservando o estado de memória da aplicação. Isso é feito através da serializaçãodo estado da aplicação e, em seguida, desserialização após as classes serem recarregados.Isto é feito com a configuração básica do Eclipse com o Tomcat. Se a UI for marcada com@PreserveOnRefresh, você pode precisar passar o parâmetro ?restartApplication naURL para forçar a reinicialização ao recarregar a página. Ferramentas como o JRebel vão além,recarregando o código, sem necessidade de serialização. O servidor também pode serializar oestado da aplicação ao desligar e reiniciar, preservando, assim, as sessões entre reinícios.

A serialização requer que as aplicações sejam serializáveis, ou seja, todas as classesimplementam a interface Serializable. Todas as classes Vaadin implementam. Se vocêestendê-las ou implementar as interfaces, você pode fornecer uma chave de serialização opcional,que é gerada automaticamente pelo Eclipse, se você usá-lo. A serialização também é usadapara o agrupamento e computação em nuvem, como o Google App Engine, como descrito emSecção 11.7, “Google App Engine Integration”.

4.7.2. Servlet Vaadin, Portlet, e Serviço

O VaadinServlet, ou VaadinPortlet em um portal, recebe todas as requisições do servidormapeado para a sua URL, conforme definido na configuração de implantação, e as associa comas sessões, que associam as requisições com UIs particulares.

Ao atender requisições, o servlet ou portlet Vaadin lida com todas as tarefas comuns a ambosservlets e portlets em um VaadinService. Ele gerencia sessões, dá acesso às informações deconfiguração de implantação, lida com mensagens do sistema, e faz várias outras tarefas.Quaisquer outras tarefas específicas de servlet ou portlet são tratadas no VaadinServletServiceou VaadinPortletService correspondente. O serviço funciona como a camada de customizaçãode baixo nível primária para o processamento de requisições.

Customizando um Servlet Vaadin

Muitas tarefas de configuração comuns precisam ser feitas na classe servlet, que você já tem,se estiver usando a anotação @WebServlet para Servlet 3.0 para implantar a aplicação. Vocêpode lidar com mais customizações, sobrescrevendo o método servletInitialized(), ondeo objeto VaadinService está disponível pelo getService() (não estaria disponível em umconstrutor). Você deve sempre chamar super.servletInitialized() no início.

public class MyServlet extends VaadinServlet {@Overrideprotected void servletInitialized()throws ServletException {super.servletInitialized();...}}

Para adicionar funcionalidades customizadas na manipulação de requisições, você podesobrescrever o método service().

Para usar a classe servlet customizada em um projeto com Servlet 2.4, você precisa informá-lono descritor de implantação web.xml, no lugar da classe VaadinServlet regular, conformedescrito em Secção 4.8.4, “Usando um Descritor de Implantação web.xml”.

Servlet Vaadin, Portlet, e Serviço96

Escrevendo uma Aplicação Web de Lado Servidor

Page 99: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Customizando o Vaadin Portlet

To Be Done

Customizando o Vaadin Service

Para customizar o VaadinService, primeiro você precisa estender a classe VaadinServlet ouPortlet e sobrescrever o método createServletService() para criar um objeto de serviçocustomizado.

4.7.3. Sessão de Usuário

Uma sessão de usuário começa quando um usuário faz uma requisição para um servlet ouportlet Vaadin abrindo a URL para uma UI particular. Todas as requisições de servidorpertencentes a uma classe de UI particular são processadas pela classe VaadinServlet ouVaadinPortlet. Quando um novo cliente conecta-se, ele cria uma nova sessão de usuário,representada por uma instância de VaadinSession. As sessões são rastreadas usando cookiesarmazenados no navegador.

Você pode obter a VaadinSession de uma UI com getSession() ou globalmente comVaadinSession.getCurrent().Também é fornecido acesso aos objetos de sessão de baixonível, HttpSession e PortletSession, através de uma WrappedSession. Você tambémpode acessar a configuração de implantação através da VaadinSession, conforme descrito emSecção 4.8.7, “Configuração de Implantação”.

A sessão termina após a última instância de UI expirar ou ser fechada, como descritoposteriormente.

Manipulando Inicialização e Destruição de Sessão

Você pode lidar com a inicialização e destruição de sessão através da implementação de umSessionInitListener e SessionDestroyListener, respectivamente, para oVaadinService. Você pode fazer isso melhor, estendendo VaadinServlet e sobrescrevendo ométodo servletInitialized(), conforme descrito em Secção 4.7.2, “Servlet Vaadin, Portlet,e Serviço”.

public class MyServlet extends VaadinServletimplements SessionInitListener, SessionDestroyListener {@Overrideprotected void servletInitialized() throws ServletException {super.servletInitialized();getService().addSessionInitListener(this);getService().addSessionDestroyListener(this);}@Overridepublic void sessionInit(SessionInitEvent event)throws ServiceException {// Faça coisas da sessão aqui}@Overridepublic void sessionDestroy(SessionDestroyEvent event) {// Faça coisas da finalização aqui}}

97Sessão de Usuário

Escrevendo uma Aplicação Web de Lado Servidor

Page 100: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Se usar Servlet 2.4, você precisa configurar a classe de servlet customizada com o parâmetroservlet-class no descritor web.xml em vez de VaadinServlet, como descrito emSecção 4.8.4, “Usando um Descritor de Implantação web.xml”.

4.7.4. Carregando uma UI

Quando um navegador acessa pela primeira vez uma URL mapeada para o servlet de umaclasse UI particular, o servlet Vaadin gera uma página de carregamento. A página carrega aengine do lado cliente (conjunto de widgets), que por sua vez carrega a UI em uma requisiçãoseparada para o servlet Vaadin.

Uma instância de UI é criada quando a engine do lado cliente faz sua primeira requisição. Oservlet cria as UIs utilizando um UIProvider registrado na instância de VaadinSession. Umasessão tem pelo menos um DefaultUIProvider para gerenciar UIs abertas pelo usuário. Se aaplicação permite ao usuário abrir janelas pop-up com um BrowserWindowOpener, cada umdeles tem um provedor de UI especial dedicado.

Uma vez que uma nova UI é criada, seu método init() é chamado. O método recebe arequisição como uma VaadinRequest.

Customizando a Página de Carregamento

O conteúdo HTML da página de carregamento é gerado como um objeto HTML DOM, que podeser customizado através da implementação de um BootstrapListener que modifica o objetoDOM. Para isso, você precisa estender o VaadinServlet e adicionar um SessionInitListenerao objeto de serviço, conforme descrito em Secção 4.7.3, “Sessão de Usuário”. Depois disso,você pode adicionar o ouvinte de inicialização a uma sessão com addBootstrapListener()quando a sessão é inicializada.

O carregamento do conjunto de widgets é tratado na página de carregamento com funçõesdefinidas em um script vaadinBootstrap.js separado.

Você pode customizar totalmente a página de carregamento, como em uma página HTMLestática, conforme descrito em Secção 11.2, “Embedding UIs in Web Pages”.

UI Providers Customizados

Você pode criar objetos de UI dinamicamente de acordo com os seus parâmetros de requisição,como o caminho de URL, através da definição de um UIProvider customizado. Você precisaadicionar UI providers customizados ao objeto de sessão que os chama. Os providers são ligadosde tal forma que eles são requisitados começando pelo último adicionado, até que um retornea UI. Do contrário, null será retornado. Você pode adicionar um UI provider à sessão de formamais conveniente através da implementação de um servlet customizado e da adição de um UIprovider às sessões em um SessionInitListener.

Você pode encontrar um exemplo de UI providers customizados em Secção 20.8.1, “Providinga Fallback UI”.

Preservando a UI ao Atualizar

Recarregar uma página no navegador normalmente gera um nova instância de UI e a velha UIé deixada suspensa, até que seja limpa após um tempo. Isto pode ser indesejável, uma vez queredefine o estado da UI para o usuário. Para preservar a UI, você pode usar a anotação@PreserveOnRefresh na classe de UI. Você também pode usar um UIProvider com umaimplementação customizada do isUiPreserved().

Carregando uma UI98

Escrevendo uma Aplicação Web de Lado Servidor

Page 101: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

@PreserveOnRefreshpublic class MyUI extends UI {

Adicionar o parâmetro ?restartApplication na URL avisa ao servlet Vaadin para criar umanova instância de UI ao carregar a página, sobrescrevendo assim o @PreserveOnRefresh.Isso é muitas vezes necessário ao desenvolver a UI no Eclipse, quando você precisa reiniciarapós a reimplatanção, porque o Eclipse gosta de manter o estado da aplicação entrereimplantações. Se incluir algum fragmento URI, o parâmetro deve ser dado antes do fragmento.

4.7.5. Expiração de UI

Instâncias de UI são limpas, se nenhuma comunicação é recebida delas por algum tempo. Senão são feitas mais requisições ao servidor, o lado cliente envia requisições de manutenção defuncionamento (keep-alive) heartbeats. A UI é mantida viva enquanto requisições ou heartbeatssão recebidos dela. Ele expira quando três heartbeats consecutivos são perdidos.

Os heartbeats ocorrem em um intervalo de cinco minutos, o que pode ser alterado com oparâmetro heartbeatInterval do servlet. Você pode configurar o parâmetro com@VaadinServletConfiguration ou no web.xml, conforme descrito em Secção 4.8.6, “OutrosParâmetros de Configuração de Servlet”.

Quando a limpeza da UI ocorre, um DetachEvent é enviado para todos os DetachListenersadicionados à UI. Quando a UI é desatachada da sessão, detach() é chamado para ela.

4.7.6. Expiração de Sessão

Uma sessão é mantida viva através de requisições do servidor causadas pela interação dousuário com a aplicação, bem como pelo monitoramento dos heartbeats das UIs. Uma vez quetodas as UIs tenham expirado, a sessão ainda permanece. Ela é limpa a partir do servidor,quando o timeout da sessão configurado na aplicação web expira.

Se houver UIs ativas em uma aplicação, seus heartbeats mantém a sessão viva indefinidamente.Você pode ter timeout de sessões se o usuário estiver inativo por muito tempo, que é o propósitooriginal da configuração de timeout. Se o parâmetro closeIdleSessions do servlet éconfigurado para true no web.xml, como descrito em Secção 4.8.4, “Usando um Descritor deImplantação web.xml”, a sessão e todas suas UIs são fechadas quando o timeout especificadopelo parâmetro session-timeout do servlet expira, após a última requisição não heartbeat.Uma vez que a sessão seja encerrada, o navegador irá mostrar um erro de sincronização napróxima requisição de servidor. Para evitar a mensagem feia, você pode definir uma URL deredirecionamento para as UIs, como descrito em Secção 4.5.2, “Customizando Mensagens doSistema”.

Os parâmetros de configuração relacionados são descritos em Secção 4.8.6, “Outros Parâmetrosde Configuração de Servlet”.

Você pode lidar com a expiração de sessões no lado servidor com umSessionDestroyListener, conforme descrito em Secção 4.7.3, “Sessão de Usuário”.

4.7.7. Fechando uma Sessão

Você pode chamar o método close() em VaadinSession para encerrar a sessão e limpar osrecursos alocados para ela. A sessão é fechada imediatamente e todos os objetos relacionadosficam indisponíveis após chamar o método. A UI que ainda é visível no navegador não temsessão para se comunicar, mas ainda receberá a resposta do pedido final. Você normalmente

99Expiração de UI

Escrevendo uma Aplicação Web de Lado Servidor

Page 102: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

quer redirecionar o usuário para outra URL neste ponto, usando o método setLocation() emPage.

No exemplo a seguir, exibimos um botão de logout, que fecha a sessão do usuário.

Button logout = new Button("Logout");logout.addClickListener(new Button.ClickListener() {@Overridepublic void buttonClick(ClickEvent event) {// Redireciona para outra páginagetUI().getPage().setLocation("/myapp/logoutpage.html");// Fecha a VaadinSessiongetSession().close();}});

4.8. Implantando uma Aplicação

Aplicações Vaadin são implantados como aplicações Java web, que podem conter uma sériede servlets, cada um deles pode ser uma aplicação Vaadin ou algum outro servlet, e recursosestáticos, como arquivos HTML. Uma aplicação web normalmente é empacotada como umarquivo WAR (Web application ARchive), que pode ser implantado em um servidor de aplicaçõesJava (ou um contêiner de servlets para ser exato). Um arquivo WAR, que tem extensão .war,é um subtipo de JAR (Java ARchive), e como um JAR regular, é um arquivo compactado ZIPcom uma estrutura de conteúdo especial.

Para um tutorial detalhado sobre como aplicações web são empacotadas, por favor, consultequalquer livro que fale sobre Servlets Java.

No jargão de Servlet Java, uma "aplicação web" significa um conjunto de servlets ou portletsJava, páginas JSP e HTML estáticas, e vários outros recursos que formam uma aplicação. Talaplicação web Java normalmente é empacotada como um pacote WAR para implantação. UIsVaadin de lado servidor rodam como servlets dentro de tal aplicação web Java. Há tambémoutros tipos de aplicações web. Para evitar confusão com o significado geral de "aplicação web",freqüentemente nos referimos a aplicações web em Java neste livro com o ligeiro equívoco"WAR".

4.8.1. Criando um WAR Implantável no Eclipse

Para implantar uma aplicação em um servidor web, você precisa criar um pacote WAR. Aquinós damos as instruções para o Eclipse.

1. Selecione File   Export e então Web   WAR File. Ou, clique com o botão direito sobreo projeto no Project Explorer e selecione Web   WAR File.

2. Selecione Web project para exportar. Digite o nome do arquivo em Destination .war).

3. Faça outras configurações na caixa de diálogo e clique em Finish.

4.8.2. Conteúdo de Aplicações Web

Os seguintes arquivos são necessários em uma aplicação web a fim de executá-la.

Implantando uma Aplicação100

Escrevendo uma Aplicação Web de Lado Servidor

Page 103: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Organização de Aplicações Web

WEB-INF/web.xml (opcional com Servlet 3.0)Este é o descritor da aplicação web que define como a aplicação é organizada, ouseja, quais servlets e o que ela tem. Você pode consultar qualquer livro Java sobre oconteúdo deste arquivo. Isso não é necessário se você definir o servlet Vaadin coma anotação @WebServlet na API Servlet 3.0.

WEB-INF/lib/*.jarEstas são as bibliotecas Vaadin e suas dependências. Elas podem ser encontradasno pacote de instalação ou carregadas por um sistema de gerenciamento dedependências tal como Maven ou Ivy.

Suas classes de UIVocê deve incluir suas classes de UI em um arquivo JAR em WEB-INF/lib ou comoclasses em WEB-INF/classes

Seus próprios arquivos de tema (OPCIONAL)Se sua aplicação usa um tema especial (look and feel), você deve incluí-lo no diretórioVAADIN/themes/themename.

Conjuntos de widgets (OPCIONAL)Se sua aplicação usa um conjunto de widgets específico do projeto, ele deve sercompilado no diretório VAADIN/widgetset/.

4.8.3. Classe de Servlet Web

Ao utilizar a API Servlet 3.0, você normalmente declara as classes de servlet Vaadin com aanotação @WebServlet. A UI Vaadin associada ao servlet e outros parâmetros específicos doVaadin são declarados com uma anotação @VaadinServletConfiguration separada.

@WebServlet(value = "/*",asyncSupported = true)@VaadinServletConfiguration(productionMode = false,ui = MyProjectUI.class)public class MyProjectServlet extends VaadinServlet {}

O Plugin Vaadin para Eclipse cria a classe de servlet como uma classe interna estática na classede UI. Normalmente, você pode querer tê-lo como uma classe regular separada.

O parâmetro value é o padrão de URL para mapear URLs de requisição para servlets, conformedescrito em Secção 4.8.5, “Mapeamento de Servlets com Padrões de URL”. O parâmetro ui éa classe de UI. O modo de produção é desabilitado por padrão, o que habilita a compilação detema on-the-fly, janela de depuração, e outras funcionalidades de desenvolvimento. Consulteas seções seguintes para obter detalhes sobre os diferentes servlet e os parâmetros deconfiguração Vaadin.

Você também pode usar um descritor de implantação web.xml em projetos Servlet 3.0.

4.8.4. Usando um Descritor de Implantação web.xml

Um descritor de implantação é um arquivo XML de nome web.xml no sub-diretório WEB-INFde uma aplicação web. É um componente padrão de Java EE, que descreve como uma aplicação

101Classe de Servlet Web

Escrevendo uma Aplicação Web de Lado Servidor

Page 104: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

web deve ser implantada. O descritor não é necessário para a API Servlet 3.0, onde você tambémpode definir servlets com a anotação @WebServlet, conforme descrito anteriormente, comofragmentos web, ou programaticamente. Você pode usar ambos, web.xml e WebServlet, namesma aplicação. Definições no web.xml sobrescrevem as anotações.

O exemplo a seguir mostra o conteúdo básico de um descritor de implantação para um aplicaçãoServlet 2.4. Basta especificar a classe de UI com o parâmetro UI comocom.vaadin.server.VaadinServlet. O servlet é então mapeado para uma URL de forma padrãopara Servlets Java.

<?xml version="1.0" encoding="UTF-8"?><web-appid="WebApp_ID" version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><servlet><servlet-name>myservlet</servlet-name><servlet-class>com.vaadin.server.VaadinServlet</servlet-class><init-param><param-name>UI</param-name><param-value>com.ex.myprj.MyUI</param-value></init-param><!-- If not using the default widget set--><init-param><param-name>widgetset</param-name><param-value>com.ex.myprj.MyWidgetSet</param-value></init-param></servlet><servlet-mapping><servlet-name>myservlet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping></web-app>

O descritor define um servlet com o nome myservlet. A classe servlet,com.vaadin.server.VaadinServlet, é fornecida pelo framework Vaadin e é normalmente amesma para todos os projetos Vaadin. Para alguns propósitos, pode ser necessário usar umaclasse servlet customizada que estende VaadinServlet. O nome da classe deve incluir o caminhocompleto do pacote.

Versão da API Servlet

O exemplo de descritor dado acima foi para o Servlet 2.4. Para uma versão mais recente, comoServlet 3.0, você deve usar:

<web-appid="WebApp_ID" version="3.0"xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

O suporte a Servlet 3.0 é útil, pelo menos, para o push de servidor.

Usando um Descritor de Implantação web.xml102

Escrevendo uma Aplicação Web de Lado Servidor

Page 105: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Conjunto de Widgets

Se a UI utiliza componentes add-ons ou widgets customizados, é necessário um conjunto dewidgets customizado, que pode ser especificado com o parâmetro widgetset no servlet.Alternativamente, você pode definir com a anotação @WidgetSet na classe de UI. O parâmetroé o nome da classe com o mesmo caminho, mas sem a extensão .gwt.xml do arquivo dedefinição do conjunto de widgets. Se o parâmetro não for fornecido,com.vaadin.DefaultWidgetSet é usado. Ele contém todos os widgets para os componentes doVaadin.

A menos que o conjunto de widgets padrão seja utilizado, (que está incluso no JAR vaadin-client-compiled), o conjunto de widgets deve ser compilado, conforme descrito emCapítulo 17, Using Vaadin Add-ons ou Secção 13.4, “Compiling a Client-Side Module”, edevidamente implantado com a aplicação.

4.8.5. Mapeamento de Servlets com Padrões de URL

O servlet precisa ser mapeado para um caminho de URL, que o solicita para requisições.

Com a anotação @WebServlet na classe de servlet:

@WebServlet(value = "/*", asyncSupported = true)

Em um web.xml:

<servlet-mapping><servlet-name>myservlet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>

O padrão de URL é definido nos exemplos acima como /*. Isso corresponde a qualquer URLsob o contexto do projeto. Definimos acima o contexto do projeto como myproject, logo, aURL da página da UI será http://localhost:8080/myproject/.

Mapeando Sub Caminhos

Se uma aplicação tem várias UIs ou servlets, eles precisam ter caminhos diferentes na URL,correspondidos por um padrão de URL diferente. Além disso, você pode precisar ter conteúdoestático em algum caminho. Ter um padrão de URL /myui/* corresponderia a uma URL comohttp://localhost:8080/myproject/myui/. Note que a barra e o asterisco devem serincluídos no final do padrão. Nesse caso, você também precisa mapear URLs com /VAADIN/*para um servlet (a menos que você disponibilize-o estaticamente como indicado abaixo).

Com uma anotação @WebServlet na classe de servlet, você pode definir vários mapeamentos,com uma lista entre chaves, da seguinte forma:

@WebServlet(value = {"/myui/*", "/VAADIN/*"},asyncSupported = true)

Em um web.xml:

...<servlet-mapping><servlet-name>myservlet</servlet-name><url-pattern>/myui/*</url-pattern></servlet-mapping><servlet-mapping>

103Mapeamento de Servlets com Padrões de URL

Escrevendo uma Aplicação Web de Lado Servidor

Page 106: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<servlet-name>myservlet</servlet-name><url-pattern>/VAADIN/*</url-pattern></servlet-mapping>

Se você tiver vários servlets, você deve especificar apenas um mapeamento /VAADIN/*. Nãoimporta qual servlet você mapeará para o padrão, desde que ele seja um servlet Vaadin.

Você não precisa fornecer o mapeamento /VAADIN/* acima, se você disponibilizar ambos osconjuntos de widgets e temas (customizado e padrão) estaticamente no diretório /VAADIN naaplicação web. O mapeamento permite simplesmente os fornecer dinamicamente a partir doJAR Vaadin. Fornecê-los estaticamente é recomendado para ambientes de produção por sermais rápido. Se você servir o conteúdo a partir da mesma aplicação web, você pode não ter opadrão de raiz /* para o servlet Vaadin, já que todos os pedidos serão mapeados para o servlet.

4.8.6. Outros Parâmetros de Configuração de Servlet

A classe servlet ou descritor de implantação podem ter muitos parâmetros e opções que controlama execução de um servlet. Você pode encontrar a documentação completa dos parâmetrosbásicos de servlet na Especificação de Servlet Java. @VaadinServletConfiguration aceita umnúmero especial de parâmetros, como descrito abaixo.

Em um web.xml, você pode definir a maioria dos parâmetros com <context-param> paratoda a aplicação web, caso em que se aplica a todos os servlets Vaadin, ou com <init-param>para um servlet individual. Se ambos estiverem definidos, os parâmetros de servlet sobrescrevemparâmetros de contexto.

Modo de Produção

Por padrão, aplicações Vaadin rodam em modo debug (ou modo de desenvolvimento), que deveser usado durante o desenvolvimento. Isso habilita várias funcionalidades de depuração. Parauso em produção, você deve ter a configuração productionMode=true no@VaadinServletConfiguration, ou no web.xml:

<context-param><param-name>productionMode</param-name><param-value>true</param-value><description>Vaadin production mode</description></context-param>

O parâmetro e os modos de depuração e de produção são descritos em mais detalhes emSecção 11.3, “Debug Mode and Window”.

UI Provider Customizado

Vaadin normalmente usa o DefaultUIProvider para criar instâncias de classe de UI. Se vocêprecisar usar um UI provider customizado, você pode definir sua classe com o parâmetroUIProvider. O provider é registrado na VaadinSession.

Em um web.xml:

<servlet>...

Outros Parâmetros de Configuração de Servlet104

Escrevendo uma Aplicação Web de Lado Servidor

Page 107: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<init-param><param-name>UIProvider</param-name><param-value>com.ex.my.MyUIProvider</param-value></init-param>

O parâmetro é associado logicamente com um servlet particular, mas pode ser definido nocontexto também.

Heartbeat de UI

Vaadin segue UIs utilizando um heartbeat, como explicado em Secção 4.7.5, “Expiração de UI”.Se o usuário fechar a janela do navegador de uma aplicação Vaadin ou navegar para outrapágina, a engine de lado cliente em funcionamento na página pára de enviar heartbeats para oservidor, e ele eventualmente limpa a instância de UI.

O intervalo de requisições heartbeat pode ser especificado em segundos com o parâmetroheartbeatInterval tanto como um parâmetro de contexto para toda a aplicação web ou umparâmetro de inicialização para o servlet individual. O valor padrão é 300 segundos (5 minutos).

Em um web.xml:

<context-param><param-name>heartbeatInterval</param-name><param-value>300</param-value></context-param>

Timeout de Sessão Após Inatividade do Usuário

Na operação normal do servlet, o timeout da sessão define o tempo permitido de inatividadeapós o qual o servidor deve limpar a sessão. A inatividade é medida a partir do último pedidodo servidor. Contêiners de servlet diferentes usam padrões diferentes para timeouts, como 30minutos para o Apache Tomcat. Você pode definir o timeout sob <web-app> com:

Em um web.xml:

<session-config><session-timeout>30</session-timeout></session-config>

O timeout da sessão deve ser mais longo que o intervalo de heartbeat. Do contrário, sessõessão fechadas antes que o heartbeat possa mantê-las vivas. Como a expiração da sessão deixaas UIs em um estado onde elas assumem que a sessão ainda existe, isso poderia causar umerro de falta de sincronização no navegador.

No entanto, ter um intervalo de heartbeat mais curto que o timeout da sessão, que é o casonormal, impede que as sessões expirem. Se o parâmetro closeIdleSessions do servlet estáhabilitado (desativado por padrão), Vaadin fecha as UIs e a sessão após o tempo especificadono parâmetro session-timeout expirar, após a última requisição não heartbeat.

Em um web.xml:

105Outros Parâmetros de Configuração de Servlet

Escrevendo uma Aplicação Web de Lado Servidor

Page 108: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<servlet>...<init-param><param-name>closeIdleSessions</param-name><param-value>true</param-value></init-param>

Modo Push

Você pode ativar o push de servidor para uma UI tanto com a anotação @Push na UI como nodescritor, conforme descrito em Secção 11.16, “Server Push”. O modo push é definido com oparâmetro pushmode. O modo automático envia mudanças para o navegador automaticamentedepois que access() termina. Com o modo manual, você precisa enviar explicitamente compush(). Se você usar um servidor compartilhado Servlet 3.0, você também pode habilitar oprocessamento assíncrono com o parâmetro async-supported.

Em um web.xml:

<servlet>...<init-param><param-name>pushmode</param-name><param-value>automatic</param-value></init-param><async-supported>true</async-supported>

Prevenção de Cross-Site Request Forgery

Vaadin usa um mecanismo de proteção para evitar cross-site request forgery (XSRF or CSRF)mal-intencionado, também chamados de ataques de um clique ou session riding, que é umaexploração de segurança para executar comandos não autorizados num servidor web. Estaproteção é normalmente habilitada. No entanto, isso impede algumas formas de testar aplicaçõesVaadin, tais como o JMeter. Nesses casos, você pode desabilitar a proteção, definindo oparâmetro disable-xsrf-protection para true.

Em um web.xml:

<context-param><param-name>disable-xsrf-protection</param-name><param-value>true</param-value></context-param>

4.8.7. Configuração de Implantação

Os parâmetros específicos do Vaadin, definidos na configuração de implantação, estão disponíveisa partir do objeto DeploymentConfiguration, gerenciado pela VaadinSession.

DeploymentConfiguration conf =getSession().getConfiguration();// Intervalo de heartbeat em segundosint heartbeatInterval = conf.getHeartbeatInterval();

Parâmetros na definição de Servlet Java, como o timeout da sessão, estão disponíveis a partirdos objetos de baixo nível HttpSession e PortletSession, que são encapsulados em uma

Configuração de Implantação106

Escrevendo uma Aplicação Web de Lado Servidor

Page 109: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

WrappedSession no Vaadin. Você pode acessar o wrapper da sessão de baixo nível com ogetSession() da VaadinSession.

WrappedSession session = getSession().getSession();int sessionTimeout = session.getMaxInactiveInterval();

Você também pode acessar outras propriedades das sessões HttpSession e PortletSessionatravés da interface, como mudar e ler atributos da sessão que são compartilhados por todosos servlets pertencentes a uma sessão de servlet ou portlet particular.

107Configuração de Implantação

Escrevendo uma Aplicação Web de Lado Servidor

Page 110: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

108

Page 111: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 5

User InterfaceComponents

5.1. Overview ................................................................................................ 1105.2. Interfaces and Abstractions ................................................................... 1115.3. Common Component Features ............................................................. 1135.4. Field Components ................................................................................. 1245.5. Component Extensions ......................................................................... 1305.6. Label ..................................................................................................... 1305.7. Link ....................................................................................................... 1335.8. TextField ............................................................................................... 1355.9. TextArea ............................................................................................... 1405.10. PasswordField .................................................................................... 1415.11. RichTextArea ...................................................................................... 1415.12. Date and Time Input with DateField .................................................... 1435.13. Button ................................................................................................. 1485.14. CheckBox ........................................................................................... 1495.15. Selection Components ........................................................................ 1505.16. Table .................................................................................................... 1635.17. Tree ..................................................................................................... 1825.18. MenuBar ............................................................................................. 1835.19. Embedded Resources ......................................................................... 1865.20. Upload ................................................................................................ 189

109Book of Vaadin

Page 112: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.21. ProgressBar ....................................................................................... 1915.22. Slider ................................................................................................... 1945.23. Calendar ............................................................................................. 1965.24. Component Composition with CustomComponent ........................... 2135.25. Composite Fields with CustomField ................................................... 214

This chapter provides an overview and a detailed description of all non-layout components inVaadin.

Because of pressing release schedules to get this edition to your hands, some topics still requirerevision for Vaadin 7, especially the data binding of the Table component. Please consult theweb version once it is updated, or the next print edition.

5.1. Overview

Vaadin provides a comprehensive set of user interface components and allows you to definecustom components. Figura 5.1, “User Interface Component Class Hierarchy” illustrates theinheritance hierarchy of the UI component classes and interfaces. Interfaces are displayed ingray, abstract classes in orange, and regular classes in blue. An annotated version of the diagramis featured in the Vaadin Cheat Sheet.

At the top of the interface hierarchy, we have the Component interface. At the top of the classhierarchy, we have the AbstractComponent class. It is inherited by two other abstract classes:AbstractField, inherited further by field components, and AbstractComponentContainer,inherited by various container and layout components. Components that are not bound to acontent data model, such as labels and links, inherit AbstractComponent directly.

The layout of the various components in a window is controlled, logically, by layout components,just like in conventional Java UI toolkits for desktop applications. In addition, with theCustomLayout component, you can write a custom layout as an XHTML template that includesthe locations of any contained components. Looking at the inheritance diagram, we can see thatlayout components inherit the AbstractComponentContainer and the Layout interface. Layoutcomponents are described in detail in Capítulo 6, Managing Layout.

Looking at it from the perspective of an object hierarchy, we would have a Window object, whichcontains a hierachy of layout components, which again contain other layout components, fieldcomponents, and other visible components.

You can browse the built-in UI components of Vaadin library in the Sampler application of theVaadin Demo. The Sampler shows a description, JavaDoc documentation, and a code samplesfor each of the components.

In addition to the built-in components, many components are available as add-ons, either fromthe Vaadin Directory or from independent sources. Both commercial and free components exist.The installation of add-ons is described in Capítulo 17, Using Vaadin Add-ons.

Vaadin Cheat Sheet and Refcard

Figura 5.1, “User Interface Component Class Hierarchy” is included in the VaadinCheat Sheet that illustrates the basic relationship hierarchy of the user interfacecomponents and data binding classes and interfaces. You can download it athttp://vaadin.com/book.

Overview110

User Interface Components

Page 113: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.1. User Interface Component Class Hierarchy

The diagram is also included in the six-page DZone Refcard, which you can find athttps://vaadin.com/refcard.

5.2. Interfaces and Abstractions

Vaadin user interface components are built on a skeleton of interfaces and abstract classes thatdefine and implement the features common to all components and the basic logic how thecomponent states are serialized between the server and the client.

This section gives details on the basic component interfaces and abstractions. The layout andother component container abstractions are described in Capítulo 6, Managing Layout. Theinterfaces that define the Vaadin data model are described in Capítulo 9, Binding Componentsto Data.

All components also implement the Paintable interface, which is used for serializing ("painting")the components to the client, and the reverse VariableOwner interface, which is needed fordeserializing component state or user interaction from the client.

111Interfaces and Abstractions

User Interface Components

Page 114: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.2. Component Interfaces and Abstractions

In addition to the interfaces defined within the Vaadin framework, all components implement thejava.io.Serializable interface to allow serialization. Serialization is needed in many clusteringand cloud computing solutions.

5.2.1. Component Interface

The Component interface is paired with the AbstractComponent class, which implements allthe methods defined in the interface.

Component Tree Management

Components are laid out in the user interface hierarchically. The layout is managed by layoutcomponents, or more generally components that implement the ComponentContainer interface.Such a container is the parent of the contained components.

The getParent() method allows retrieving the parent component of a component. While thereis a setParent(), you rarely need it as you usually add components with the addComponent()method of the ComponentContainer interface, which automatically sets the parent.

A component does not know its parent when the component is still being created, so you can notrefer to the parent in the constructor with getParent().

Attaching a component to an UI triggers a call to its attach() method. Correspondingly, removinga component from a container triggers calling the detach() method. If the parent of an addedcomponent is already connected to the UI, the attach() is called immediately fromsetParent().

public class AttachExample extends CustomComponent { public AttachExample() { }

Component Interface112

User Interface Components

Page 115: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

@Override public void attach() { super.attach(); // Must call.

// Now we know who ultimately owns us. ClassResource r = new ClassResource("smiley.jpg"); Image image = new Image("Image:", r); setCompositionRoot(image); }}

The attachment logic is implemented in AbstractComponent, as described in Secção 5.2.2,“AbstractComponent”.

5.2.2. AbstractComponent

AbstractComponent is the base class for all user interface components. It is the (only)implementation of the Component interface, implementing all the methods defined in the interface.

AbstractComponent has a single abstract method, getTag(), which returns the serializationidentifier of a particular component class. It needs to be implemented when (and only when)creating entirely new components. AbstractComponent manages much of the serialization ofcomponent states between the client and the server. Creation of new components and serializationis described in Capítulo 16, Integrating with the Server-Side.

5.3. Common Component Features

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

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

5.3.1. Caption

A caption is an explanatory textual label accompanying a user interface component, usuallyshown 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 text can usually be given as the first parameter of a constructor of a component orwith setCaption().

// 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 orcomponent container inside which the component is placed. For example, the VerticalLayoutcomponent shows the captions left-aligned above the contained components, while theFormLayout 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. TheCustomComponent does not manage the caption of its composition root, so if the root componenthas a caption, it will not be rendered.

113AbstractComponent

User Interface Components

Page 116: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.3. Caption Management by VerticalLayout and FormLayoutcomponents.

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

Icon (see Secção 5.3.4, “Icon”) is closely related to caption and is usually displayed horizontallybefore or after it, depending on the component and the containing layout. Also the requiredindicator in field components is usually shown before or after the caption.

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

CSS Style Rules

.v-caption {} .v-captiontext {} .v-caption-clearelem {} .v-required-field-indicator {}

A caption is be rendered inside an HTML element that has the v-caption CSS style class.Thecontaining layout may enclose a caption inside other caption-related elements.

Some layouts put the caption text in a v-captiontext element. A v-caption-clearelemis used in some layouts to clear a CSS float property in captions. An optional required indicatorin field components is contained in a separate element with v-required-field-indicatorstyle.

5.3.2. Description and Tooltips

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 overthe 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 Figura 5.4, “Component Description as a Tooltip”.

Description and Tooltips114

User Interface Components

Page 117: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.4. Component Description as a Tooltip

A description is rendered as a tooltip in most components.

When a component error has been set with setComponentError(), the error is usually alsodisplayed in the tooltip, below the description. Components that are in error state will also displaythe error indicator. See Secção 4.5.1, “Indicador e Mensagem de Erro”.

The description is actually not plain text, but you can use XHTML tags to format it. Such a richtext 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 Figura 5.5, “A Rich Text Tooltip”.

Figura 5.5. A Rich Text Tooltip

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

5.3.3. Enabled

The enabled property controls whether the user can actually use the component. A disabledcomponent is visible, but grayed to indicate the disabled state.

Components are always enabled by default. You can disable a component withsetEnabled(false).

Button enabled = new Button("Enabled");enabled.setEnabled(true); // The defaultlayout.addComponent(enabled);

Button disabled = new Button("Disabled");disabled.setEnabled(false);layout.addComponent(disabled);

Figura 5.6, “An Enabled and Disabled Button” shows the enabled and disabled buttons.

115Enabled

User Interface Components

Page 118: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.6. An Enabled and Disabled Button

A disabled component is automatically put in read-only state. No client interaction with such acomponent is sent to the server and, as an important security feature, the server-side componentsdo not receive state updates from the client in the read-only state. This feature exists in all built-in components in Vaadin and is automatically handled for all Field components for the fieldproperty value. For custom widgets, you need to make sure that the read-only state is checkedon the server-side for all safety-critical variables.

CSS Style Rules

Disabled components have the v-disabled CSS style in addition to the component-specificstyle. To match a component with both the styles, you have to join the style class names with adot as done in the example below.

.v-textfield.v-disabled { border: dotted;}

This would make the border of all disabled text fields dotted.

TextField disabled = new TextField("Disabled");disabled.setValue("Read-only value");disabled.setEnabled(false);layout.addComponent(disabled);

The result is illustrated in Figura 5.7, “Styling Disabled Components”.

Figura 5.7. Styling Disabled Components

In Valo theme, the opacity of disabled components is specified with the $v-disabled-opacityparameter, as described in Secção 8.6.2, “Common Settings”.

5.3.4. Icon

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

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

// Component with an icon from a custom themeTextField 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");

Icon116

User Interface Components

Page 119: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

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 orcomponent container in which the component is placed. For example, the VerticalLayoutcomponent shows the icons left-aligned above the contained components, while the FormLayoutcomponent shows the icons on the left side of the vertically laid components, with the icons andtheir associated components left-aligned in their own columns. The CustomComponent doesnot manage the icon of its composition root, so if the root component has an icon, it will not berendered.

Figura 5.8. Displaying an Icon from a Theme Resource.

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

In addition to image resources, you can use font icons, which are icons included in special fonts,but which are handled as special resources. See Secção 11.17, “Font Icons” for more details.

CSS Style Rules

An icon will be rendered inside an HTML element that has the v-icon CSS style class. Thecontaining layout may enclose an icon and a caption inside elements related to the caption, suchas v-caption.

5.3.5. Locale

The locale property defines the country and language used in a component. You can use thelocale 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() as follows:

// Component for which the locale is meaningfulInlineDateField 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(Resolution.DAY);layout.addComponent(date);

The resulting date field is shown in Figura 5.9, “Set Locale for InlineDateField”.

117Locale

User Interface Components

Page 120: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.9. Set Locale for InlineDateField

Getting the Locale

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

The getLocale() returns null if the component is not yet attached to the UI, which is usuallythe case in most constructors, so it is a bit awkward to use it for internationalization.You can getthe locale in attach(), as shown in the following example:

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

However, it is normally a better practice to use the locale of the current UI to get the localizedresource right when the component is created.

// Captions are stored in MyAppCaptions resource bundle// and the UI object is known in this context.ResourceBundle bundle = ResourceBundle.getBundle(MyAppCaptions.class.getName(), UI.getCurrent().getLocale());

// Get a localized resource from the bundleButton cancel = new Button(bundle.getString(MyAppCaptions.CancelKey));layout.addComponent(cancel);

Selecting a Locale

A common task in many applications is selecting a locale. This is done in the following examplewith a ComboBox, which gets the available locales in Java.

// The locale in which we want to have the language// selection listLocale displayLocale = Locale.ENGLISH;

// All known localesfinal Locale[] locales = Locale.getAvailableLocales();

Locale118

User Interface Components

Page 121: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// 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 ComboBox select = new ComboBox("Select a language") { @Override public void attach() { super.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 localefinal Label localeCode = new Label("");layout.addComponent(localeCode);

// A date field which language the selection will changefinal InlineDateField date = new InlineDateField("Calendar in the selected language");date.setResolution(Resolution.DAY);layout.addComponent(date);

// Handle language selectionselect.addValueChangeListener(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 Figura 5.10, “Selecting a Locale”.

119Locale

User Interface Components

Page 122: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.10. Selecting a Locale

5.3.6. Read-Only

The property defines whether the value of a component can be changed. The property is mainlyapplicable to Field components, as they have a value that can be edited by the user.

TextField readwrite = new TextField("Read-Write");readwrite.setValue("You can change this");readwrite.setReadOnly(false); // The defaultlayout.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 Figura 5.11, “A Read-Only Component.”.

Figura 5.11. A Read-Only Component.

Setting a layout or some other component container as read-only does not usually make thecontained components read-only recursively. This is different from, for example, the disabledstate, which is usually applied recursively.

Notice that the value of a selection component is the selection, not its items. A read-only selectioncomponent doesn't therefore allow its selection to be changed, but other changes are possible.For example, if you have a read-only Table in editable mode, its contained fields and the underlyingdata model can still be edited, and the user could sort it or reorder the columns.

Client-side state modifications will not be communicated to the server-side and, more importantly,server-side field components will not accept changes to the value of a read-only Field component.The latter is an important security feature, because a malicious user can not fabricate statechanges in a read-only field. This is handled at the level of AbstractField in setValue(), soyou can not change the value programmatically either. Calling setValue() on a read-only fieldresults in Property.ReadOnlyException.

Also notice that while the read-only status applies automatically to the property value of a field,it does not apply to other component variables. A read-only component can accept some othervariable changes from the client-side and some of such changes could be acceptable, such aschange in the scroll bar position of a Table. Custom widgets should check the read-only statefor variables bound to business data.

Read-Only120

User Interface Components

Page 123: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

CSS Style Rules

Setting a normally editable component to read-only state can change its appearance to disallowediting the value. In addition to CSS styling, also the HTML structure can change. For example,TextField loses the edit box and appears much like a Label.

A read-only component will have the v-readonly style. The following CSS rule would makethe text in all read-only TextField components appear in italic.

.v-textfield.v-readonly { font-style: italic;}

5.3.7. Style Name

The style name property defines one or more custom CSS style class names for the component.The getStyleName() returns the current style names as a space-separated list. ThesetStyleName() replaces all the styles with the given style name or a space-separated list ofstyle names. You can also add and remove individual style names with addStylename() andremoveStyleName(). A style name must be a valid CSS style name.

Label label = new Label("This text has a lot of style");label.addStyleName("mystyle");layout.addComponent(label);

The style name will appear in the component's HTML element in two forms: literally as given andprefixed with the component-specific style name. For example, if you add a style name mystyleto a Button, the component would get both mystyle and v-button-mystyle styles. Neitherform may conflict with built-in style names of Vaadin. For example, focus style would conflictwith a built-in style of the same name, and an content style for a Panel component wouldconflict with the built-in v-panel-content style.

The following CSS rule would apply the style to any component that has the mystyle style.

.mystyle { font-family: fantasy; font-style: italic; font-size: 25px; font-weight: bolder; line-height: 30px;}

The resulting styled component is shown in Figura 5.12, “Component with a Custom Style”

Figura 5.12. Component with a Custom Style

5.3.8. Visible

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

121Style Name

User Interface Components

Page 124: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

TextField invisible = new TextField("No-see-um");invisible.setValue("You can't see this!");invisible.setVisible(false);layout.addComponent(invisible);

The resulting invisible component is shown in Figura 5.13, “An Invisible Component.”.

Figura 5.13. An Invisible Component.

Beware that invisible beings can leave footprints.The containing layout cell that holds the invisiblecomponent will not go away, but will show in the layout as extra empty space. Also expand ratioswork just like if the component was visible - it is the layout cell that expands, not the component.

If you need to make a component only cosmetically invisible, you should use a custom theme toset it display: none style.This is mainly useful for some special components that have effectseven when made invisible in CSS. If the hidden component has undefined size and is enclosedin a layout that also has undefined size, the containing layout will collapse when the componentdisappears. If you want to have the component keep its size, you have to make it invisible bysetting all its font and other attributes to be transparent. In such cases, the invisible content ofthe component can be made visible easily in the browser.

A component made invisible with the visible property has no particular CSS style class to indicatethat it is hidden.The element does exist though, but has display: none style, which overridesany CSS styling.

5.3.9. Sizing Components

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

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

The size of a component can be set with setWidth() and setHeight() methods.The methodstake the size as a floating-point value. You need to give the unit of the measure as the secondparameter for the above methods.The available units are listed in Tabela 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 theHTML/CSS standards for specifying measures.

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

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

Sizing Components122

User Interface Components

Page 125: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

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

You always need to keep in mind that a layout with undefined size may not contain componentswith defined relative size, such as "full size". See Secção 6.13.1, “Layout Size” for details.

The Tabela 5.1, “Size Units” lists the available units and their codes defined in the Sizeableinterface.

Tabela 5.1. Size Units

The pixel is the basic hardware-specific measure of onephysical display pixel.

pxUNITS_PIXELS

The point is a typographical unit, which is usually defined as1/72 inches or about 0.35 mm. However, on displays the sizecan vary significantly depending on display metrics.

ptUNITS_POINTS

The pica is a typographical unit, defined as 12 points, or 1/7inches or about 4.233 mm. On displays, the size can varydepending on display metrics.

pcUNITS_PICAS

A unit relative to the used font, the width of the upper-case "M"letter.

emUNITS_EM

A unit relative to the used font, the height of the lower-case "x"letter.

exUNITS_EX

A physical length unit, millimeters on the surface of a displaydevice. However, the actual size depends on the display, itsmetrics in the operating system, and the browser.

mmUNITS_MM

A physical length unit, centimeters on the surface of a displaydevice. However, the actual size depends on the display, itsmetrics in the operating system, and the browser.

cmUNITS_CM

A physical length unit, inches on the surface of a display device.However, the actual size depends on the display, its metricsin the operating system, and the browser.

inUNITS_INCH

A relative percentage of the available size. For example, forthe top-level layout 100% would be the full width or height of

%UNITS_PERCENTAGE

the browser window. The percentage value must be between0 and 100.

If a component inside HorizontalLayout or VerticalLayout has full size in the namesake directionof the layout, the component will expand to take all available space not needed by the othercomponents. See Secção 6.13.1, “Layout Size” for details.

5.3.10. Managing Input Focus

When the user clicks on a component, the component gets the input focus, which is indicated byhighlighting according to style definitions. If the component allows inputting text, the focus andinsertion point are indicated by a cursor. Pressing the Tab key moves the focus to the componentnext in the focus order.

Focusing is supported by all Field components and also by Upload.

123Managing Input Focus

User Interface Components

Page 126: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The focus order or tab index of a component is defined as a positive integer value, which youcan set with setTabIndex() and get with getTabIndex(). The tab index is managed in thecontext of the page in which the components are contained. The focus order can therefore jumpbetween two any lower-level component containers, such as sub-windows or panels.

The default focus order is determined by the natural hierarchical order of components in the orderin which they were added under their parents. The default tab index is 0 (zero).

Giving a negative integer as the tab index removes the component from the focus order entirely.

CSS Style Rules

The component having the focus will have an additional style class with the -focus suffix. Forexample, a TextField, which normally has the v-textfield style, would additionally have thev-textfield-focus style.

For example, the following would make a text field blue when it has focus.

.v-textfield-focus { background: lightblue;}

5.4. Field Components

Fields are components that have a value that the user can change through the user interface.Figura 5.14, “Field Components” illustrates the inheritance relationships and the importantinterfaces and base classes.

Field components are built upon the framework defined in the Field interface and theAbstractField base class. AbstractField is the base class for all field components. In additionto the component features inherited from AbstractComponent, it implements a number offeatures defined in Property, Buffered, Validatable, and Component.Focusable interfaces.

The description of the field interfaces and base classes is broken down in the following sections.

5.4.1. Field Interface

The Field interface inherits the Component superinterface and also the Property interface tohave a value for the field. AbstractField is the only class implementing the Field interface directly.The relationships are illustrated in Figura 5.15, “Field Interface Inheritance Diagram”.

Field Components124

User Interface Components

Page 127: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.14. Field Components

125Field Interface

User Interface Components

Page 128: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.15. Field Interface Inheritance Diagram

You can set the field value with the setValue() and read with the getValue() method definedin the Property interface. The actual value type depends on the component.

The Field interface defines a number of attributes, which you can retrieve or manipulate with thecorresponding setters and getters.

descriptionAll fields have a description. Notice that while this attribute is defined in the Fieldcomponent, it is implemented in AbstractField, which does not directly implementField, but only through the AbstractField class.

requiredWhen enabled, a required indicator (usually the asterisk * character) is displayed onthe left, above, or right the field, depending on the containing layout and whether thefield has a caption. If such fields are validated but are empty and the requiredErrorproperty (see below) is set, an error indicator is shown and the component error is setto the text defined with the error property. Without validation, the required indicator ismerely a visual guide.

requiredErrorDefines the error message to show when a value is required, but none is entered.Theerror message is set as the component error for the field and is usually displayed in atooltip when the mouse pointer hovers over the error indicator.

5.4.2. Data Binding and Conversions

Fields are strongly coupled with the Vaadin data model.The field value is handled as a Propertyof the field component, as documented in Secção 9.2, “Properties”. Selection fields allowmanagement of the selectable items through the Container interface.

Fields are editors for some particular type. For example, TextField allows editing String values.When bound to a data source, the property type of the data model can be something different,say an Integer. Converters are used for converting the values between the representation andthe model. They are described in Secção 9.2.3, “Converting Between Property Type andRepresentation”.

Data Binding and Conversions126

User Interface Components

Page 129: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.4.3. Handling Field Value Changes

Field inherits Property.ValueChangeListener to allow listening for field value changes andProperty.Editor to allow editing values.

When the value of a field changes, a Property.ValueChangeEvent is triggered for the field.Youshould not implement the valueChange() method in a class inheriting AbstractField, as it isalready implemented in AbstractField. You should instead implement the method explicitly byadding the implementing object as a listener.

5.4.4. Field Buffering

Field components implement the Buffered and BufferedValidatable interfaces. Whenbuffering is enabled for a field with setBuffered(true), the value is not written to the propertydata source before the commit() method is called for the field. Calling commit() also runsvalidators added to the field, and if any fail (and the invalidCommitted is disabled), the valueis not written.

form.addComponent(new Button("Commit", new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { try { editor.commit(); } catch (InvalidValueException e) { Notification.show(e.getMessage()); } }}));

Calling discard() reads the value from the property date source to the current input.

If the fields are bound in a FieldGroup that has buffering enabled, calling commit() for thegroup runs validation on all fields in the group, and if successful, all the field values are writtento the item data source. See Secção 9.4.4, “Buffering Forms”.

5.4.5. Field Validation

The input for a field component can be syntactically or semantically invalid. Fields implement theValidatable interface, which allows checking validity of the input with validators that implementthe Validator interface.You can add validators to fields with addValidator().

TextField field = new TextField("Name");field.addValidator(new StringLengthValidator( "The name must be 1-10 letters (was {0})", 1, 10, true));layout.addComponent(field);

Failed validation is indicated with the error indicator of the field, described in Secção 4.5.1,“Indicador e Mensagem de Erro”, unless disabled with setValidationVisible(false).Hovering mouse on the field displays the error message given as a parameter for the validator.If validated explicitly with validate(), as described later, the InvalidValueException is thrownif the validation fails, also carrying the error message. The value {0} in the error message stringis replaced with the invalid input value.

127Handling Field Value Changes

User Interface Components

Page 130: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Validators validate the property type of the field after a possible conversion, not the presentationtype. For example, an IntegerRangeValidator requires that the value type of the property datasource is Integer.

Built-in Validators

Vaadin includes the following built-in validators. The property value type is indicated.

BeanValidatorValidates a bean property according to annotations defined in the Bean Validation API1.0 (JSR-303).This validator is usually not used explicitly, but they are created implicitlywhen binding fields in a BeanFieldGroup. Using bean validation requires animplementation library of the API. See Secção 9.4.6, “Bean Validation” for details.

CompositeValidatorCombines validators using logical AND and OR operators.

DateRangeValidator: DateChecks that the date value is within the range at or between two given dates/times.

DoubleRangeValidator: DoubleChecks that the double value is at or between two given values.

EmailValidator: StringChecks that the string value is a syntactically valid email address.The validated syntaxis close to the RFC 822 standard regarding email addresses.

IntegerRangeValidator: IntegerChecks that the integer value is at or between two given values.

NullValidatorChecks that the value is or is not a null value.

RegexpValidator: StringChecks that the value matches with the given regular expression.

StringLengthValidator: StringChecks that the length of the input string is at or between two given lengths.

Please see the API documentation for more details.

Automatic Validation

The validators are normally, when validationVisible is true for the field, executed implicitlyon the next server request if the input has changed. If the field is in immediate mode, it (and anyother fields with changed value) are validated immediately when the focus leaves the field.

TextField field = new TextField("Name");field.addValidator(new StringLengthValidator( "The name must be 1-10 letters (was {0})", 1, 10, true));field.setImmediate(true);layout.addComponent(field);

Field Validation128

User Interface Components

Page 131: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Explicit Validation

The validators are executed when the validate() or commit() methods are called for thefield.

// A field with automatic validation disabledfinal TextField field = new TextField("Name");layout.addComponent(field);

// Define validation as usualfield.addValidator(new StringLengthValidator( "The name must be 1-10 letters (was {0})", 1, 10, true));

// Run validation explicitlyButton validate = new Button("Validate");validate.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { field.setValidationVisible(false); try { field.validate(); } catch (InvalidValueException e) { Notification.show(e.getMessage()); field.setValidationVisible(true); } }});layout.addComponent(validate);

Implementing a Custom Validator

You can create custom validators by implementing the Validator interface and implementingits validate() method. If the validation fails, the method should throw eitherInvalidValueException or EmptyValueException.

class MyValidator implements Validator { @Override public void validate(Object value) throws InvalidValueException { if (!(value instanceof String && ((String)value).equals("hello"))) throw new InvalidValueException("You're impolite"); }}

final TextField field = new TextField("Say hello");field.addValidator(new MyValidator());field.setImmediate(true);layout.addComponent(field);

Validation in Field Groups

If the field is bound to a FieldGroup, described in Secção 9.4, “Creating Forms by Binding Fieldsto Items”, calling commit() for the group runs the validation for all the fields in the group, andif successful, writes the input values to the data source.

129Field Validation

User Interface Components

Page 132: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.5. Component Extensions

Components and UIs can have extensions which are attached to the component dynamically.Especially, many add-ons are extensions.

How a component is extended depends on the extension. Typically, they have an extend()method that takes the component to be extended as the parameter.

TextField tf = new TextField("Hello");layout.addComponent(tf);

// Add a simple extensionnew CapsLockWarning().extend(tf);

// Add an extension that requires some parametersCSValidator validator = new CSValidator();validator.setRegExp("[0-9]*");validator.setErrorMessage("Must be a number");validator.extend(tf);

Development of custom extensions is described in Secção 16.7, “Component and UI Extensions”.

5.6. Label

Label is a text component that displays non-editable text. In addition to regular text, you can alsodisplay preformatted text and HTML, depending on the content mode of the label.

// A container that is 100% wide by defaultVerticalLayout layout = new VerticalLayout();

Label label = new Label("Labeling can be dangerous");layout.addComponent(label);

The text will wrap around and continue on the next line if it exceeds the width of the Label. Thedefault width is 100%, so the containing layout must also have a defined width. Some layoutcomponents have undefined width by default, such as HorizontalLayout, so you need to payspecial care with them.

// A container with a defined width. The default content layout// of Panel is VerticalLayout, which has 100% default width.Panel panel = new Panel("Panel Containing a Label");panel.setWidth("300px");

panel.addComponent( new Label("This is a Label inside a Panel. There is " + "enough text in the label to make the text " + "wrap when it exceeds the width of the panel."));

As the size of the Panel in the above example is fixed and the width of Label is the default 100%,the text in the Label will wrap to fit the panel, as shown in Figura 5.16, “The Label Component”.

Component Extensions130

User Interface Components

Page 133: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.16.The Label Component

Setting Label to undefined width will cause it to not wrap at the end of the line, as the width ofthe content defines the width. If placed inside a layout with defined width, the Label will overflowthe layout horizontally and, normally, be truncated.

Even though Label is text and often used as a caption, it also has a caption, just like any othercomponent. As with other components, the caption is managed by the containing layout.

5.6.1. Content Mode

The contents of a label are formatted depending on the content mode. By default, the text isassumed to be plain text and any contained XML-specific characters will be quoted appropriatelyto allow rendering the contents of a label in HTML in a web browser. The content mode can beset in the constructor or with setContentMode(), and can have the values defined in theContentMode enumeration type in com.vaadin.shared.ui.label package:

TEXTThe default content mode where the label contains only plain text. All characters areallowed, including the special <, >, and & characters in XML or HTML, which are quotedproperly in HTML while rendering the component. This is the default mode.

PREFORMATTEDContent mode where the label contains preformatted text. It will be, by default, renderedwith a fixed-width typewriter font. Preformatted text can contain line breaks, written inJava with the \n escape sequence for a newline character (ASCII 0x0a), or tabulatorcharacters written with \t (ASCII 0x08).

HTMLContent mode where the label contains (X)HTML. The content will be enclosed in aD I V e l e m e n t h a v i n g t h e n a m e s p a c e"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd".

Please note the following security and validity warnings regarding the HTML contentmode.

Cross-Site Scripting Warning

Having Label in HTML content mode allows pure HTML content. If the content comesfrom user input, you should always carefully sanitize it to prevent cross-site scripting(XSS) attacks. Please see Secção 11.8.1, “Sanitizing User Input to Prevent Cross-Site Scripting”.

131Content Mode

User Interface Components

Page 134: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Also, the validity of the HTML content is not checked when rendering the componentand any errors can result in an error in the browser. If the content comes from anuncertain source, you should always validate it before displaying it in the component.

The following example demonstrates the use of Label in different modes.

GridLayout labelgrid = new GridLayout (2,1);

labelgrid.addComponent (new Label ("PREFORMATTED"));labelgrid.addComponent ( new Label ("This is a preformatted label.\n"+ "The newline character \\n breaks the line.", Label.ContentMode.PREFORMATTED));

labelgrid.addComponent (new Label ("TEXT"));labelgrid.addComponent ( new Label ("This is a label in (plain) text mode", Label.ContentMode.TEXT));

labelgrid.addComponent (new Label ("HTML"));labelgrid.addComponent ( new Label ("<i>This</i> is an <b>HTML</b> formatted label", Label.ContentMode.HTML));

layout.addComponent(labelgrid);

The rendering will look as follows:

Figura 5.17. Label Modes Rendered on Screen

5.6.2. Spacing with a Label

You can use a Label to create vertical or horizontal space in a layout. If you need a empty "line"in a vertical layout, having just a label with empty text is not enough, as it will collapse to zeroheight. The same goes for a label with only whitespace as the label text.You need to use a non-breaking space character, either &nbsp; or &#160;:

layout.addComponent(new Label("&nbsp;", Label.ContentMode.XHTML));

Using the Label.ContentMode.PREFORMATTED mode has the same effect; preformattedspaces do not collapse in a vertical layout. In a HorizontalLayout, the width of a space character

Spacing with a Label132

User Interface Components

Page 135: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

may be unpredictable if the label font is proportional, so you can use the preformatted mode toadd em-width wide spaces.

If you want a gap that has adjustable width or height, you can use an empty label if you specifya height or width for it. For example, to create vertical space in a VerticalLayout:

Label gap = new Label();gap.setHeight("1em");verticalLayout.addComponent(gap);

You can make a flexible expanding spacer by having a relatively sized empty label with 100%height or width and setting the label as expanding in the layout.

// A wide component barHorizontalLayout horizontal = new HorizontalLayout();horizontal.setWidth("100%");

// Have a component before the gap (a collapsing cell)Button button1 = new Button("I'm on the left");horizontal.addComponent(button1);

// An expanding gap spacerLabel expandingGap = new Label();expandingGap.setWidth("100%");horizontal.addComponent(expandingGap);horizontal.setExpandRatio(expandingGap, 1.0f);

// A component after the gap (a collapsing cell)Button button2 = new Button("I'm on the right");horizontal.addComponent(button2);

5.6.3. CSS Style Rules

The Label component has a v-label overall style.

The Reindeer theme includes a number of predefined styles for typical formatting cases. Theseinclude "h1" (Reindeer.LABEL_H1) and "h2" (Reindeer.LABEL_H2) heading styles and"light" (Reindeer.LABEL_SMALL) style.

5.7. Link

The Link component allows making hyperlinks. References to locations are represented asresource objects, explained in Secção 4.4, “Imagens e Outros Recursos”. The Link is a regularHTML hyperlink, that is, an <a href> anchor element that is handled natively by the browser.Unlike when clicking a Button, clicking a Link does not cause an event on the server-side.

Links to an arbitrary URL can be made by using an ExternalResource as follows:

// Textual linkLink link = new Link("Click Me!", new ExternalResource("http://vaadin.com/"));

You can use setIcon() to make image links as follows:

// Image linkLink iconic = new Link(null, new ExternalResource("http://vaadin.com/"));iconic.setIcon(new ThemeResource("img/nicubunu_Chain.png"));

133CSS Style Rules

User Interface Components

Page 136: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Image + captionLink combo = new Link("To appease both literal and visual", new ExternalResource("http://vaadin.com/"));combo.setIcon(new ThemeResource("img/nicubunu_Chain.png"));

The resulting links are shown in Figura 5.18, “Link Example”. You could add a "display:block" style for the icon element to place the caption below it.

Figura 5.18. Link Example

With the simple constructor used in the above example, the resource is opened in the currentwindow. Using the constructor that takes the target window as a parameter, or by setting thetarget window with setTargetName(), you can open the resource in another window, such asa popup browser window/tab. As the target name is an HTML target string managed by thebrowser, the target can be any window, including windows not managed by the application itself.You can use the special underscored target names, such as _blank to open the link to a newbrowser window or tab.

// Hyperlink to a given URLLink link = new Link("Take me a away to a faraway land", new ExternalResource("http://vaadin.com/"));

// Open the URL in a new window/tablink.setTargetName("_blank");

// Indicate visually that it opens in a new window/tablink.setIcon(new ThemeResource("icons/external-link.png"));link.addStyleName("icon-after-caption");

Normally, the link icon is before the caption.You can have it right of the caption by reversing thetext direction in the containing element.

/* Position icon right of the link caption. */.icon-after-caption { direction: rtl;}/* Add some padding around the icon. */.icon-after-caption .v-icon { padding: 0 3px;}

The resulting link is shown in Figura 5.19, “Link That Opens a New Window”.

Figura 5.19. Link That Opens a New Window

Link134

User Interface Components

Page 137: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

With the _blank target, a normal new browser window is opened. If you wish to open it in apopup window (or tab), you need to give a size for the window with setTargetWidth() andsetTargetHeight(). You can control the window border style with setTargetBorder(),which takes any of the defined border styles TARGET_BORDER_DEFAULT,TARGET_BORDER_MINIMAL, and TARGET_BORDER_NONE. The exact result depends on thebrowser.

// Open the URL in a popuplink.setTargetName("_blank");link.setTargetBorder(Link.TARGET_BORDER_NONE);link.setTargetHeight(300);link.setTargetWidth(400);

In addition to the Link component, Vaadin allows alternative ways to make hyperlinks.The Buttoncomponent has a Reindeer.BUTTON_LINK style name that makes it look like a hyperlink, whilehandling clicks in a server-side click listener instead of in the browser. Also, you can makehyperlinks (or any other HTML) in a Label in XHTML content mode.

5.7.1. CSS Style Rules

.v-link { } a { } .v-icon {} span {}

The overall style for the Link component is v-link. The root element contains the <a href>hyperlink anchor. Inside the anchor are the icon, with v-icon style, and the caption in a textspan.

Hyperlink anchors have a number of pseudo-classes that are active at different times. An unvisitedlink has a:link class and a visited link a:visited. When the mouse pointer hovers over thelink, it will have a:hover, and when the mouse button is being pressed over the link, thea:active class.When combining the pseudo-classes in a selector, please notice that a:hovermust come after an a:link and a:visited, and a:active after the a:hover.

5.8. TextField

TextField is one of the most commonly used user interface components. It is a Field componentthat allows entering textual values using keyboard.

The following example creates a simple text field:

// Create a text fieldTextField tf = new TextField("A Field");

// Put some initial content in ittf.setValue("Stuff in the field");

See the result in Figura 5.20, “TextField Example”.

Figura 5.20. TextField Example

135CSS Style Rules

User Interface Components

Page 138: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Value changes are handled with a Property.ValueChangeListener, as in most other fields. Thevalue can be acquired with getValue() directly from the text field, as is done in the examplebelow, or from the property reference of the event.

// Handle changes in the valuetf.addValueChangeListener(new Property.ValueChangeListener() { private static final long serialVersionUID = -6549081726526133772L;

public void valueChange(ValueChangeEvent event) { // Assuming that the value type is a String String value = (String) event.getProperty().getValue();

// Do something with the value Notification.show("Value is: " + value); }});

// Fire value changes immediately when the field loses focustf.setImmediate(true);

Much of the API of TextField is defined in AbstractTextField, which allows different kinds oftext input fields, such as rich text editors, which do not share all the features of the single-linetext fields.

Figura 5.21.Text Field Class Relationships

5.8.1. Data Binding

TextField edits String values, but you can bind it to any property type that has a proper converter,as described in Secção 9.2.3, “Converting Between Property Type and Representation”.

// Have an initial data model. As Double is unmodificable and// doesn't support assignment from String, the object is// reconstructed in the wrapper when the value is changed.Double trouble = 42.0;

// Wrap it in a property data sourcefinal ObjectProperty<Double> property = new ObjectProperty<Double>(trouble);

// Create a text field bound to it// (StringToDoubleConverter is used automatically)TextField tf = new TextField("The Answer", property);

Data Binding136

User Interface Components

Page 139: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

tf.setImmediate(true);

// Show that the value is really written back to the// data source when edited by user.Label feedback = new Label(property);feedback.setCaption("The Value");

When you put a Table in editable mode or create fields with a FieldGroup, theDefaultFieldFactory creates a TextField for almost every property type by default. You oftenneed to make a custom factory to customize the creation and to set the field tooltip, validation,formatting, and so on.

See Capítulo 9, Binding Components to Data for more details on data binding, field factories forTable in Secção 5.16.3, “Editing the Values in a Table”, and Secção 9.4, “Creating Forms byBinding Fields to Items” regarding forms.

5.8.2. String Length

The setMaxLength() method sets the maximum length of the input string so that the browserprevents the user from entering a longer one. As a security feature, the input value is automaticallytruncated on the server-side, as the maximum length setting could be bypassed on the client-side. The maximum length property is defined at AbstractTextField level.

Notice that the maximum length setting does not affect the width of the field. You can set thewidth with setWidth(), as with other components. Using em widths is recommended to betterapproximate the proper width in relation to the size of the used font. There is no standard wayin HTML for setting the width exactly to a number of letters (in a monospaced font).You can trickyour way around this restriction by putting the text field in an undefined-width VerticalLayouttogether with an undefined-width Label that contains a sample text, and setting the width of thetext field as 100%. The layout will get its width from the label, and the text field will use that.

5.8.3. Handling Null Values

As with any field, the value of a TextField can be set as null.This occurs most commonly whenyou create a new field without setting a value for it or bind the field value to a data source thatallows null values. In such case, you might want to show a special value that stands for the nullvalue.You can set the null representation with the setNullRepresentation() method. Mosttypically, you use an empty string for the null representation, unless you want to differentiate froma string that is explicitly empty.The default null representation is "null", which essentially warnsthat you may have forgotten to initialize your data objects properly.

The setNullSettingAllowed() controls whether the user can actually input a null value byusing the null value representation. If the setting is false, which is the default, inputting the nullvalue representation string sets the value as the literal value of the string, not null. This defaultassumption is a safeguard for data sources that may not allow null values.

// Create a text field without setting its valueTextField tf = new TextField("Field Energy (J)");tf.setNullRepresentation("-- null-point energy --");

// The null value is actually the defaulttf.setValue(null);

// Allow user to input the null value by// its representationtf.setNullSettingAllowed(true);

137String Length

User Interface Components

Page 140: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Feedback to see the valueLabel value = new Label(tf);value.setCaption("Current Value:");

The Label, which is bound to the value of the TextField, displays a null value as empty. Theresulting user interface is shown in Figura 5.22, “Null Value Representation”.

Figura 5.22. Null Value Representation

5.8.4.Text Change Events

Often you want to receive a change event immediately when the text field value changes. Theimmediate mode is not literally immediate, as the changes are transmitted only after the fieldloses focus. In the other extreme, using keyboard events for every keypress would make typingunbearably slow and also processing the keypresses is too complicated for most purposes. Textchange events are transmitted asynchronously soon after typing and do not block typing whilean event is being processed.

Text change events are received with a TextChangeListener, as is done in the following examplethat demonstrates how to create a text length counter:

// Text field with maximum lengthfinal TextField tf = new TextField("My Eventful Field");tf.setValue("Initial content");tf.setMaxLength(20);

// Counter for input lengthfinal Label counter = new Label();counter.setValue(tf.getValue().length() + " of " + tf.getMaxLength());

// Display the current length interactively in the countertf.addTextChangeListener(new TextChangeListener() { public void textChange(TextChangeEvent event) { int len = event.getText().length(); counter.setValue(len + " of " + tf.getMaxLength()); }});

// The lazy mode is actually the defaulttf.setTextChangeEventMode(TextChangeEventMode.LAZY);

The result is shown in Figura 5.23, “Text Change Events”.

Figura 5.23.Text Change Events

Text Change Events138

User Interface Components

Page 141: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The text change event mode defines how quickly the changes are transmitted to the server andcause a server-side event. Lazier change events allow sending larger changes in one event ifthe user is typing fast, thereby reducing server requests.

You can set the text change event mode of a TextField with setTextChangeEventMode().The allowed modes are defined in TextChangeEventMode enum and are as follows:

TextChangeEventMode.LAZY (default)An event is triggered when there is a pause in editing the text.The length of the pausecan be modified with setInputEventTimeout(). As with the TIMEOUT mode, atext change event is forced before a possible ValueChangeEvent, even if the userdid not keep a pause while entering the text.

This is the default mode.

TextChangeEventMode.TIMEOUTA text change in the user interface causes the event to be communicated to theapplication after a timeout period. If more changes are made during this period, theevent sent to the server-side includes the changes made up to the last change. Thelength of the timeout can be set with setInputEventTimeout().

If a ValueChangeEvent would occur before the timeout period, a TextChangeEventis triggered before it, on the condition that the text content has changed since theprevious TextChangeEvent.

TextChangeEventMode.EAGERAn event is triggered immediately for every change in the text content, typically causedby a key press. The requests are separate and are processed sequentially one afteranother. Change events are nevertheless communicated asynchronously to the server,so further input can be typed while event requests are being processed.

5.8.5. CSS Style Rules

.v-textfield { }

The HTML structure of TextField is extremely simple, consisting only of an element with thev-textfield style.

For example, the following custom style uses dashed border:

.v-textfield-dashing { border: thin dashed; background: white; /* Has shading image by default */}

The result is shown in Figura 5.24, “Styling TextField with CSS”.

Figura 5.24. Styling TextField with CSS

The style name for TextField is also used in several components that contain a text input field,even if the text input is not an actual TextField. This ensures that the style of different text inputboxes is similar.

139CSS Style Rules

User Interface Components

Page 142: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.9. TextArea

TextArea is a multi-line version of the TextField component described in Secção 5.8, “TextField”.

The following example creates a simple text area:

// Create the areaTextArea area = new TextArea("Big Area");

// Put some content in itarea.setValue("A row\n"+ "Another row\n"+ "Yet another row");

The result is shown in Figura 5.25, “TextArea Example”.

Figura 5.25. TextArea Example

You can set the number of visible rows with setRows() or use the regular setHeight() todefine the height in other units. If the actual number of rows exceeds the number, a verticalscrollbar will appear. Setting the height with setRows() leaves space for a horizontal scrollbar,so the actual number of visible rows may be one higher if the scrollbar is not visible.

You can set the width with the regular setWidth() method. Setting the size with the em unit,which is relative to the used font size, is recommended.

5.9.1. Word Wrap

The setWordwrap() sets whether long lines are wrapped (true - default) when the line lengthreaches the width of the writing area. If the word wrap is disabled (false), a vertical scrollbarwill appear instead. The word wrap is only a visual feature and wrapping a long line does notinsert line break characters in the field value; shortening a wrapped line will undo the wrapping.

TextArea area1 = new TextArea("Wrapping");area1.setWordwrap(true); // The defaultarea1.setValue("A quick brown fox jumps over the lazy dog");

TextArea area2 = new TextArea("Nonwrapping");area2.setWordwrap(false);area2.setValue("Victor jagt zw&ouml;lf Boxk&auml;mpfer quer "+ "&uuml;ber den Sylter Deich");

The result is shown in Figura 5.26, “Word Wrap in TextArea”.

TextArea140

User Interface Components

Page 143: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.26. Word Wrap in TextArea

5.9.2. CSS Style Rules

.v-textarea { }

The HTML structure of TextArea is extremely simple, consisting only of an element withv-textarea style.

5.10. PasswordField

The PasswordField is a variant of TextField that hides the typed input from visual inspection.

PasswordField tf = new PasswordField("Keep it secret");

The result is shown in Figura 5.27, “PasswordField”.

Figura 5.27. PasswordField

You should note that the PasswordField hides the input only from "over the shoulder" visualobservation. Unless the server connection is encrypted with a secure connection, such as HTTPS,the input is transmitted in clear text and may be intercepted by anyone with low-level access tothe network. Also phishing attacks that intercept the input in the browser may be possible byexploiting JavaScript execution security holes in the browser.

5.10.1. CSS Style Rules

.v-textfield { }

The PasswordField does not have its own CSS style name but uses the same v-textfieldstyle as the regular TextField. See Secção 5.8.5, “CSS Style Rules” for information on stylingit.

5.11. RichTextArea

The RichTextArea field allows entering or editing formatted text. The toolbar provides all basicediting functionalities. The text content of RichTextArea is represented in HTML format.RichTextArea inherits TextField and does not add any API functionality over it. You can addnew functionality by extending the client-side components VRichTextArea and VRichTextToolbar.

141CSS Style Rules

User Interface Components

Page 144: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

As with TextField, the textual content of the rich text area is the Property of the field and canbe set with setValue() and read with getValue().

// Create a rich text areafinal RichTextArea rtarea = new RichTextArea();rtarea.setCaption("My Rich Text Area");

// Set initial content as HTMLrtarea.setValue("<h1>Hello</h1>\n" + "<p>This rich text area contains some text.</p>");

Figura 5.28. Rich Text Area Component

Above, we used context-specific tags such as <h1> in the initial HTML content. The rich textarea component does not allow creating such tags, only formatting tags, but it does preservethem unless the user edits them away. Any non-visible whitespace such as the new line character(\n) are removed from the content. For example, the value set above will be as follows whenread from the field with getValue():

<h1>Hello</h1> <p>This rich text area contains some text.</p>

The rich text area is one of the few components in Vaadin that contain textual labels.The selectionboxes in the toolbar are in English and currently can not be localized in any other way than byinheriting or reimplementing the client-side VRichTextToolbar widget. The buttons can belocalized simply with CSS by downloading a copy of the toolbar background image, editing it,and replacing the default toolbar. The toolbar is a single image file from which the individualbutton icons are picked, so the order of the icons is different from the rendered. The image filedepends on the client-side implementation of the toolbar.

.v-richtextarea-richtextexample .gwt-ToggleButton

.gwt-Image { background-image: url(img/richtextarea-toolbar-fi.png) !important;}

RichTextArea142

User Interface Components

Page 145: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.29. Regular English and a Localized Rich Text Area Toolbar

5.11.1. Cross-Site Scripting with RichTextArea

The user input from a RichTextArea is transmitted as XHTML from the browser to server-sideand is not sanitized. As the entire purpose of the RichTextArea component is to allow input offormatted text, you can not sanitize it just by removing all HTML tags. Also many attributes, suchas style, should pass through the sanitization.

See Secção 11.8.1, “Sanitizing User Input to Prevent Cross-Site Scripting” for more details onCross-Site scripting vulnerabilities and sanitization of user input.

5.11.2. CSS Style Rules

.v-richtextarea { }

.v-richtextarea .gwt-RichTextToolbar { }

.v-richtextarea .gwt-RichTextArea { }

The rich text area consists of two main parts: the toolbar with overall style .gwt-RichTextToolbar and the editor area with style .gwt-RichTextArea. The editor areaobviously contains all the elements and their styles that the HTML content contains. The toolbarcontains buttons and drop-down list boxes with the following respective style names:

.gwt-ToggleButton { }

.gwt-ListBox { }

5.12. Date and Time Input with DateField

The DateField component provides the means to display and input date and time. The fieldcomes in two variations: PopupDateField, with a numeric input box and a popup calendar view,and InlineDateField, with the calendar view always visible. The DateField base class defaultsto the popup variation.

The example below illustrates the use of the DateField baseclass, which is equivalent to thePopupDateField. We set the initial time of the date field to current time by using the defaultconstructor of the java.util.Date class.

// Create a DateField with the default styleDateField date = new DateField();

// Set the date and time to presentdate.setValue(new Date());

The result is shown in Figura 5.30, “DateField (PopupDateField) for Selecting Date and Time”.

143Cross-Site Scripting with RichTextArea

User Interface Components

Page 146: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.30. DateField (PopupDateField) for Selecting Date and Time

5.12.1. PopupDateField

The PopupDateField provides date input using a text box for the date and time. As the DateFielddefaults to this component, the use is exactly the same as described earlier. Clicking the handleright of the date opens a popup view for selecting the year, month, and day, as well as time. Alsothe Down key opens the popup. Once opened, the user can navigate the calendar using thecursor keys.

The date and time selected from the popup are displayed in the text box according to the defaultdate and time format of the current locale, or as specified with setDateFormat(). The sameformat definitions are used for parsing user input.

Date and Time Format

The date and time are normally displayed according to the default format for the current locale(see Secção 5.3.5, “Locale”).You can specify a custom format with setDateFormat(). It takesa format string that follows the format of the SimpleDateFormat in Java.

// Display only year, month, and day in ISO formatdate.setDateFormat("yyyy-MM-dd");

The result is shown in Figura 5.31, “Custom Date Format for PopupDateField”.

Figura 5.31. Custom Date Format for PopupDateField

The same format specification is also used for parsing user-input date and time, as describedlater.

Handling Malformed User Input

A user can easily input a malformed or otherwise invalid date or time. DateField has two validationlayers: first on the client-side and then on the server-side.

The validity of the entered date is first validated on the client-side, immediately when the inputbox loses focus. If the date format is invalid, the v-datefield-parseerror style is set.Whetherthis causes a visible indication of a problem depends on the theme.The built-in reindeer theme

PopupDateField144

User Interface Components

Page 147: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

does not shown any indication by default, making server-side handling of the problem moreconvenient.

.mydate.v-datefield-parseerror .v-textfield { background: pink;}

The setLenient(true) setting enables relaxed interpretation of dates, so that invalid dates,such as February 30th or March 0th, are wrapped to the next or previous month, for example.

The server-side validation phase occurs when the date value is sent to the server. If the datefield is set in immediate state, it occurs immediately after the field loses focus. Once this is doneand if the status is still invalid, an error indicator is displayed beside the component. Hoveringthe mouse pointer over the indicator shows the error message.

You can handle the errors by overriding the handleUnparsableDateString() method. Themethod gets the user input as a string parameter and can provide a custom parsing mechanism,as shown in the following example.

// Create a date field with a custom parsing and a// custom error message for invalid formatPopupDateField date = new PopupDateField("My Date") { @Override protected Date handleUnparsableDateString(String dateString) throws Property.ConversionException { // Try custom parsing String fields[] = dateString.split("/"); if (fields.length >= 3) { try { int year = Integer.parseInt(fields[0]); int month = Integer.parseInt(fields[1])-1; int day = Integer.parseInt(fields[2]); GregorianCalendar c = new GregorianCalendar(year, month, day); return c.getTime(); } catch (NumberFormatException e) { throw new Property. ConversionException("Not a number"); } }

// Bad date throw new Property. ConversionException("Your date needs two slashes"); }};

// Display only year, month, and day in slash-delimited formatdate.setDateFormat("yyyy/MM/dd");

// Don't be too tight about the validity of dates// on the client-sidedate.setLenient(true);

The handler method must either return a parsed Date object or throw a ConversionException.Returning null will set the field value to null and clear the input box.

145PopupDateField

User Interface Components

Page 148: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Customizing the Error Message

In addition to customized parsing, overriding the handler method for unparseable input is usefulfor internationalization and other customization of the error message. You can also use it foranother way for reporting the errors, as is done in the example below:

// Create a date field with a custom error message for invalid formatPopupDateField date = new PopupDateField("My Date") { @Override protected Date handleUnparsableDateString(String dateString) throws Property.ConversionException { // Have a notification for the error Notification.show( "Your date needs two slashes", Notification.TYPE_WARNING_MESSAGE);

// A failure must always also throw an exception throw new Property.ConversionException("Bad date"); }};

If the input is invalid, you should always throw the exception; returning a null value would makethe input field empty, which is probably undesired.

Input Prompt

Like other fields that have a text box, PopupDateField allows an input prompt that is visible untilthe user has input a value.You can set the prompt with setInputPrompt.

PopupDateField date = new PopupDateField();

// Set the promptdate.setInputPrompt("Select a date");

// Set width explicitly to accommodate the promptdate.setWidth("10em");

The date field doesn't automatically scale to accommodate the prompt, so you need to set itexplicitly with setWidth().

The input prompt is not available in the DateField superclass.

CSS Style Rules

.v-datefield, v-datefield-popupcalendar {} .v-textfield, v-datefield-textfield {} .v-datefield-button {}

The top-level element of DateField and all its variants have v-datefield style.The base classand the PopupDateField also have the v-datefield-popupcalendar style.

In addition, the top-level element has a style that indicates the resolution, with v-datefield-basename and an extension, which is one of full, day, month, or year. The -full style isenabled when the resolution is smaller than a day. These styles are used mainly for controllingthe appearance of the popup calendar.

The text box has v-textfield and v-datefield-textfield styles, and the calendar buttonv-datefield-button.

PopupDateField146

User Interface Components

Page 149: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Once opened, the calendar popup has the following styles at the top level:

.v-datefield-popup {} .v-popupcontent {} .v-datefield-calendarpanel {}

The top-level element of the floating popup calendar has .v-datefield-popup style. Observethat the popup frame is outside the HTML structure of the component, hence it is not enclosedin the v-datefield element and does not include any custom styles. The content in thev-datefield-calendarpanel is the same as in InlineDateField, as described inSecção 5.12.2, “InlineDateField”.

5.12.2. InlineDateField

The InlineDateField provides a date picker component with a month view.The user can navigatemonths and years by clicking the appropriate arrows. Unlike with the popup variant, the monthview is always visible in the inline field.

// Create a DateField with the default styleInlineDateField date = new InlineDateField();

// Set the date and time to presentdate.setValue(new java.util.Date());

The result is shown in Figura 5.32, “Example of the InlineDateField”.

Figura 5.32. Example of the InlineDateField

The user can also navigate the calendar using the cursor keys.

CSS Style Rules

.v-datefield {} .v-datefield-calendarpanel {} .v-datefield-calendarpanel-header {} .v-datefield-calendarpanel-prevyear {} .v-datefield-calendarpanel-prevmonth {} .v-datefield-calendarpanel-month {} .v-datefield-calendarpanel-nextmonth {} .v-datefield-calendarpanel-nextyear {} .v-datefield-calendarpanel-body {} .v-datefield-calendarpanel-weekdays, .v-datefield-calendarpanel-weeknumbers {} .v-first {} .v-last {} .v-datefield-calendarpanel-weeknumber {} .v-datefield-calendarpanel-day {}

147InlineDateField

User Interface Components

Page 150: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

.v-datefield-calendarpanel-time {} .v-datefield-time {} .v-select {} .v-label {}

The top-level element has the v-datefield style. In addition, the top-level element has a stylename that indicates the resolution of the calendar, with v-datefield- basename and anextension, which is one of full, day, month, or year. The -full style is enabled when theresolution is smaller than a day.

The v-datefield-calendarpanel-weeknumbers and v-datefield-calendarpanel-weeknumber styles are enabled when the week numbers are enabled. The former controls theappearance of the weekday header and the latter the actual week numbers.

The other style names should be self-explanatory. For weekdays, the v-first and v-laststyles allow making rounded endings for the weekday bar.

5.12.3.Time Resolution

The DateField displays dates by default. It can also display the time in hours and minutes, orjust the month or year. The visibility of the input components is controlled by time resolution,which can be set with setResolution() method. The method takes as its parameters thelowest visible component, typically DateField.Resolution.DAY for just dates andDateField.Resolution.MIN for dates with time in hours and minutes. Please see the APIReference for the complete list of resolution parameters.

5.12.4. DateField Locale

The date and time are displayed according to the locale of the user, as reported by the browser.You can set a custom locale with the setLocale() method of AbstractComponent, as describedin Secção 5.3.5, “Locale”. Only Gregorian calendar is supported.

5.13. Button

The Button component is normally used for initiating some action, such as finalizing input informs. When the user clicks a button, a Button.ClickEvent is fired, which can be handled witha Button.ClickListener in the buttonClick() method.

You can handle button clicks with an anonymous class as follows:

Button button = new Button("Do not press this button");

button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { Notification.show("Do not press this button again"); }});

The result is shown in Figura 5.33, “An Example of a Button”. The listener can also be given inthe constructor, which is often perhaps simpler.

Time Resolution148

User Interface Components

Page 151: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.33. An Example of a Button

If you handle several buttons in the same listener, you can differentiate between them either bycomparing the Button object reference returned by the getButton() method ofButton.ClickEvent to a kept reference. For a detailed description of these patterns together withsome examples, please see Secção 3.4, “Eventos e Ouvintes”.

5.13.1. CSS Style Rules

.v-button { } .v-button-wrap { } .v-button-caption { }

A button has an overall v-button style. The caption has v-button-caption style. There isalso an intermediate wrap element, which may help in styling in some cases.

Some built-in themes contain a small style, which you can enable by addingReindeer.BUTTON_SMALL, etc.The BaseTheme also has a BUTTON_LINK style, which makesthe button look like a hyperlink.

5.14. CheckBox

CheckBox is a two-state selection component that can be either checked or unchecked. Thecaption of the check box will be placed right of the actual check box. Vaadin provides two waysto create check boxes: individual check boxes with the CheckBox component described in thissection and check box groups with the OptionGroup component in multiple selection mode, asdescribed in Secção 5.15.5, “Radio Button and Check Box Groups with OptionGroup”.

Clicking on a check box will change its state. The state is a Boolean property that you can setwith the setValue() method and obtain with the getValue() method of the Property interface.Changing the value of a check box will cause a ValueChangeEvent, which can be handled bya ValueChangeListener.

// A check box with default state (not checked, false).final CheckBox checkbox1 = new CheckBox("My CheckBox");main.addComponent(checkbox1);

// Another check box with explicitly set checked state.final CheckBox checkbox2 = new CheckBox("Checked CheckBox");checkbox2.setValue(true);main.addComponent(checkbox2);

// Make some application logic. We use anonymous listener// classes here. The above references were defined as final// to allow accessing them from inside anonymous classes.checkbox1.addValueChangeListener(new ValueChangeListener() { public void valueChange(ValueChangeEvent event) { // Copy the value to the other checkbox. checkbox2.setValue(checkbox1.getValue()); }});checkbox2.addValueChangeListener(new ValueChangeListener() {

149CSS Style Rules

User Interface Components

Page 152: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

public void valueChange(ValueChangeEvent event) { // Copy the value to the other checkbox. checkbox1.setValue(checkbox2.getValue()); }});

Figura 5.34. An Example of a Check Box

For an example on the use of check boxes in a table, see Secção 5.16, “Table”.

5.14.1. CSS Style Rules

.v-checkbox { } .v-checkbox > input { } .v-checkbox > label { }

The top-level element of a CheckBox has the v-checkbox style. It contains two sub-elements:the actual check box input element and the label element. If you want to have the label onthe left, you can change the positions with "direction: rtl" for the top element.

5.15. Selection Components

Vaadin offers many alternative ways for selecting one or more items. The core library includesthe following selection components, all based on the AbstractSelect class:

ComboBoxA drop-down list with a text box, where the user can type text to find matching items.The component also provides an input prompt and the user can enter new items.

ListSelectA vertical list box for selecting items in either single or multiple selection mode.

NativeSelectProvides selection using the native selection component of the browser, typically adrop-down list for single selection and a multi-line list in multiselect mode. This usesthe <select> element in HTML.

OptionGroupShows the items as a vertically arranged group of radio buttons in the single selectionmode and of check boxes in multiple selection mode.

TwinColSelectShows two list boxes side by side where the user can select items from a list of availableitems and move them to a list of selected items using control buttons.

In addition, the Tree, Table, and TreeTable components allow special forms of selection. Theyalso inherit the AbstractSelect.

CSS Style Rules150

User Interface Components

Page 153: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.15.1. Binding Selection Components to Data

The selection components are strongly coupled with the Vaadin Data Model.The selectable itemsin all selection components are objects that implement the Item interface and are contained ina Container. The current selection is bound to the Property interface.

Even though the data model is used, the selection components allow simple use in the mostcommon cases. Each selection component is bound to a default container type, which supportsmanagement of items without need to implement a container.

See Capítulo 9, Binding Components to Data for a detailed description of the data model, itsinterfaces, and built-in implementations.

Adding New Items

New items are added with the addItem() method defined in the Container interface.

// Create a selection componentComboBox select = new ComboBox("My ComboBox");

// Add items with given item IDsselect.addItem("Mercury");select.addItem("Venus");select.addItem("Earth");

The addItem() method creates an empty Item, which is identified by its item identifier (IID)object, given as the parameter. This item ID is by default used also as the caption of the item,as described in more detail later.

We emphasize that addItem() is a factory method that takes an item ID, not the actual item asthe parameter - the item is returned by the method. The item is of a type that is specific to thecontainer and has itself little relevance for most selection components, as the properties of anitem may not be used in any way (except in Table), only the item ID.

The item identifier is typically a string, in which case it can be used as the caption, but can beany object type. We could as well have given integers for the item identifiers and set the captionsexplicitly with setItemCaption(). You could also add an item with the parameterlessaddItem(), which returns an automatically generated item ID.

// Create a selection componentComboBox select = new ComboBox("My Select");

// Add an item with a generated IDObject itemId = select.addItem();select.setItemCaption(itemId, "The Sun");

// Select the itemselect.setValue(itemId);

Some container types may support passing the actual data object to the add method. For example,you can add items to a BeanItemContainer with addBean(). Such implementations can use aseparate item ID object, or the data object itself as the item ID, as is done in addBean(). In thelatter case you can not depend on the default way of acquiring the item caption; see the descriptionof the different caption modes later.

The following section describes the different options for determining the item captions.

151Binding Selection Components to Data

User Interface Components

Page 154: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Item Captions

The displayed captions of items in a selection component can be set explicitly withsetItemCaption() or determined from the item IDs or item properties. The captiondetermination is defined with the caption mode, any of the modes in theAbstractSelect.ItemCaptionMode enum, which you can set with setItemCaptionMode().The default mode is EXPLICIT_DEFAULTS_ID, which uses the item identifiers for the captions,unless given explicitly.

In addition to a caption, an item can have an icon. The icon is set with setItemIcon().

Caption Modes for Selection Components

ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_IDThis is the default caption mode and its flexibility allows using it in most cases. Bydefault, the item identifier will be used as the caption. The identifier object does notnecessarily have to be a string; the caption is retrieved with toString() method. Ifthe caption is specified explicitly with setItemCaption(), it overrides the itemidentifier.

// Create a selection componentComboBox select = new ComboBox("Moons of Mars");select.setItemCaptionMode(ItemCaptionMode.EXPLICIT_DEFAULTS_ID);

// Use the item ID also as the caption of this itemselect.addItem(new Integer(1));

// Set item caption for this item explicitlyselect.addItem(2); // same as "new Integer(2)"select.setItemCaption(2, "Deimos");

ITEM_CAPTION_MODE_EXPLICITCaptions must be explicitly specified with setItemCaption(). If they are not, thecaption will be empty. Such items with empty captions will nevertheless be displayedin the selection component as empty items. If they have an icon, they will be visible.

ITEM_CAPTION_MODE_ICON_ONLYOnly icons are shown, captions are hidden.

ITEM_CAPTION_MODE_IDString representation of the item identifier object is used as caption. This is usefulwhen the identifier is a string, and also when the identifier is an complex object thathas a string representation. For example:

ComboBox select = new ComboBox("Inner Planets");select.setItemCaptionMode(ItemCaptionMode.ID);

// A class that implements toString()class PlanetId extends Object implements Serializable { private static final long serialVersionUID = -7452707902301121901L;

String planetName; PlanetId (String name) { planetName = name; } public String toString () {

Binding Selection Components to Data152

User Interface Components

Page 155: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

return "The Planet " + planetName; }}

// Use such objects as item identifiersString planets[] = {"Mercury", "Venus", "Earth", "Mars"};for (int i=0; i<planets.length; i++) select.addItem(new PlanetId(planets[i]));

ITEM_CAPTION_MODE_INDEXIndex number of item is used as caption. This caption mode is applicable only to datasources that implement the Container.Indexed interface. If the interface is not available,the component will throw a ClassCastException. The AbstractSelect itself does notimplement this interface, so the mode is not usable without a separate data source.An IndexedContainer, for example, would work.

ITEM_CAPTION_MODE_ITEMString representation of item, acquired with toString(), is used as the caption.Thisis applicable mainly when using a custom Item class, which also requires using acustom Container that is used as a data source for the selection component.

ITEM_CAPTION_MODE_PROPERTYItem captions are read from the String representation of the property with the identifierspecified with setItemCaptionPropertyId(). This is useful, for example, whenyou have a container that you use as the data source for the selection component,and you want to use a specific property for caption.

In the example below, we bind a selection component to a bean container and use aproperty of the bean as the caption.

/* A bean with a "name" property. */public class Planet implements Serializable { String name;

public Planet(String name) { this.name = name; }

public void setName(String name) { this.name = name; }

public String getName() { return name; }}

void propertyModeExample(VerticalLayout layout) { // Have a bean container to put the beans in BeanItemContainer<Planet> container = new BeanItemContainer<Planet>(Planet.class);

// Put some example data in it container.addItem(new Planet(1, "Mercury")); container.addItem(new Planet(2, "Venus")); container.addItem(new Planet(3, "Earth")); container.addItem(new Planet(4, "Mars"));

153Binding Selection Components to Data

User Interface Components

Page 156: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Create a selection component bound to the container ComboBox select = new ComboBox("Planets", container);

// Set the caption mode to read the caption directly // from the 'name' property of the bean select.setItemCaptionMode(ItemCaptionMode.PROPERTY); select.setItemCaptionPropertyId("name");

...

Getting and Setting Selection

A selection component provides the current selection as the property of the component (with theProperty interface). The property value is an item identifier object that identifies the selecteditem.You can get the identifier with getValue() of the Property interface.

You can select an item with the corresponding setValue() method. In multiselect mode, theproperty will be an unmodifiable set of item identifiers. If no item is selected, the property will benull in single selection mode or an empty collection in multiselect mode.

The ComboBox and NativeSelect will show empty selection when no actual item is selected.This is the null selection item identifier. You can set an alternative ID withsetNullSelectionItemId(). Setting the alternative null ID is merely a visual text; thegetValue() will still return null value if no item is selected, or an empty set in multiselectmode.

The item identifier of the currently selected item will be set as the property of the selectioncomponent. You can access it with the getValue() method of the Property interface of thecomponent. Also, when handling selection changes with a Property.ValueChangeListener, theValueChangeEvent will have the selected item as the property of the event, accessible with thegetProperty() method.

Figura 5.35. Selected Item

5.15.2. ComboBox

The ComboBox component allows selecting an item from a drop-down list.The component alsohas a text field area, which allows entering search text by which the items shown in the drop-down list are filtered.

ComboBox154

User Interface Components

Page 157: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.36.The ComboBox Component

Filtered Selection

ComboBox allows filtering the items available for selection in the drop-down list by the textentered in the input box. Pressing Enter will complete the item in the input box. Pressing Up-and Down-arrows can be used for selecting an item from the drop-down list. The drop-down listis paged and clicking on the scroll buttons will change to the next or previous page. The listselection can also be done with the arrow keys on the keyboard. The shown items are loadedfrom the server as needed, so the number of items held in the component can be quite large.

The filtering is done according to the the filtering mode defined in the FilteringMode enum.Theyare as follows:

CONTAINSMatches any item that contains the string given in the text field part of the component.

STARTSWITHMatches only items that begin with the given string.

OFF (default)Filtering is by default off.

ComboBox combobox = new ComboBox("Enter containing substring");

// Set the filtering modecombobox.setFilteringMode(FilteringMode.CONTAINS);

// Fill the component with some itemsfinal String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };for (int i = 0; i < planets.length; i++) for (int j = 0; j < planets.length; j++) { combobox.addItem(planets[j] + " to " + planets[i]);

The above example uses the containment filter that matches to all items containing the inputstring. As shown in Figura 5.37, “Filtered Selection” below, when we type some text in the inputarea, the drop-down list will show all the matching items.

155ComboBox

User Interface Components

Page 158: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.37. Filtered Selection

CSS Style Rules

.v-filterselect { }

.v-filterselect-input { }

.v-filterselect-button { }

.v-filterselect-suggestpopup { }

.v-filterselect-prefpage-off { }

.v-filterselect-suggestmenu { }

.v-filterselect-status { }

.v-select { }

.v-select-select { }

In its default state, only the input field of the ComboBox component is visible. The entirecomponent is enclosed in v-filterselect style (a legacy remnant), the input field hasv-filterselect-input style and the button in the right end that opens and closes the drop-down result list has v-filterselect-button style.

The drop-down result list has an overall v-filterselect-suggestpopup style. It containsthe list of suggestions with v-filterselect-suggestmenu style and a status bar in the bottomwith v-filterselect-status style. The list of suggestions is padded with an area withv-filterselect-prefpage-off style above and below the list.

5.15.3. ListSelect

The ListSelect component is list box that shows the selectable items in a vertical list. If thenumber of items exceeds the height of the component, a scrollbar is shown. The componentallows both single and multiple selection modes, which you can set with setMultiSelect().It is visually identical in both modes.

// Create the selection componentListSelect select = new ListSelect("My Selection");

// Add some itemsselect.addItem("Mercury");select.addItem("Venus");select.addItem("Earth");...

ListSelect156

User Interface Components

Page 159: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

select.setNullSelectionAllowed(false);

// Show 5 items and a scrollbar if there are moreselect.setRows(5);

The number of visible items is set with setRows().

Figura 5.38.The ListSelect Component

CSS Style Rules

.v-select {} .v-select-select {} option {}

The component has an overall v-select style. The native select element has v-select-select style.

5.15.4. Native Selection Component NativeSelect

NativeSelect is a drop-down selection component implemented with the native selection inputof web browsers, using the HTML <select> element.

// Create the selection componentfinal NativeSelect select = new NativeSelect("Native Selection");

// Add some itemsselect.addItem("Mercury");select.addItem("Venus");...

// Set the width in "columns" as in TextFieldselect.setColumns(10);

select.setNullSelectionAllowed(false);

The setColumns() allows setting the width of the list as "columns", which is a measure thatdepends on the browser.

157Native Selection Component NativeSelect

User Interface Components

Page 160: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.39.The NativeSelect Component

Multiple selection mode is not allowed; you should use the ListSelect component instead.

CSS Style Rules

.v-select {} .v-select-select {}

The component has a v-select overall style. The native select element has v-select-select style.

5.15.5. Radio Button and Check Box Groups with OptionGroup

The OptionGroup class provides selection from alternatives using a group of radio buttons insingle selection mode. In multiple selection mode, the items show up as check boxes.

OptionGroup optiongroup = new OptionGroup("My Option Group");

// Use the multiple selection mode.myselect.setMultiSelect(true);

Figura 5.40, “Option Button Group in Single and Multiple Selection Mode” shows the OptionGroupin both single and multiple selection mode.

Figura 5.40. Option Button Group in Single and Multiple Selection Mode

You can create check boxes individually using the CheckBox class, as described in Secção 5.14,“CheckBox”. The advantages of the OptionGroup component are that as it maintains theindividual check box objects, you can get an array of the currently selected items easily, and thatyou can easily change the appearance of a single component.

Radio Button and Check Box Groups with OptionGroup158

User Interface Components

Page 161: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Disabling Items

You can disable individual items in an OptionGroup with setItemEnabled(). The user cannot select or deselect disabled items in multi-select mode, but in single-select mode the use canchange the selection from a disabled to an enabled item. The selections can be changedprogrammatically regardless of whether an item is enabled or disabled.You can find out whetheran item is enabled with isItemEnabled().

The setItemEnabled() identifies the item to be disabled by its item ID.

// Have an option groupOptionGroup group = new OptionGroup("My Disabled Group");group.addItem("One");group.addItem("Two");group.addItem("Three");

// Disable one itemgroup.setItemEnabled("Two", false);

The item IDs are also used for the captions in this example. The result is shown in Figura 5.41,“OptionGroup with a Disabled Item”.

Figura 5.41. OptionGroup with a Disabled Item

Setting an item as disabled turns on the v-disabled style for it.

CSS Style Rules

.v-select-optiongroup {}

.v-select-option.v-checkbox {}

.v-select-option.v-radiobutton {}

The v-select-optiongroup is the overall style for the component. Each check box will havethe v-checkbox style, borrowed from the CheckBox component, and each radio button thev-radiobutton style. Both the radio buttons and check boxes will also have the v-select-option style that allows styling regardless of the option type. Disabled items have additionallythe v-disabled style.

The options are normally laid out vertically. You can use horizontal layout by setting display:inline-block for the options. The nowrap setting for the overall element prevents wrappingif there is not enough horizontal space in the layout, or if the horizontal width is undefined.

/* Lay the options horizontally */.v-select-optiongroup-horizontal .v-select-option { display: inline-block;}

/* Avoid wrapping if the layout is too tight */.v-select-optiongroup-horizontal { white-space: nowrap;}

159Radio Button and Check Box Groups with OptionGroup

User Interface Components

Page 162: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

/* Some extra spacing is needed */.v-select-optiongroup-horizontal .v-select-option.v-radiobutton { padding-right: 10px;}

Use of the above rules requires setting a custom horizontal style name for the component.The result is shown in Figura 5.42, “Horizontal OptionGroup”.

Figura 5.42. Horizontal OptionGroup

5.15.6.Twin Column Selection with TwinColSelect

The TwinColSelect field provides a multiple selection component that shows two lists side byside, with the left column containing unselected items and the right column the selected items.The user can select items from the list on the left and click on the ">>" button to move them tothe list on the right. Items can be deselected by selecting them in the right list and clicking on the"<<" button.

TwinColSelect is always in multi-select mode, so its property value is always a collection of theitem IDs of the selected items, that is, the items in the right column.

The selection columns can have their own captions, separate from the overall component caption,which is managed by the containing layout. You can set the column captions withsetLeftColumnCaption() and setRightColumnCaption().

final TwinColSelect select = new TwinColSelect("Select Targets to Destroy");

// Set the column captions (optional)select.setLeftColumnCaption("These are left");select.setRightColumnCaption("These are done for");

// Put some data in the selectString planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};for (int pl=0; pl<planets.length; pl++) select.addItem(planets[pl]);

// Set the number of visible itemsselect.setRows(planets.length);

The resulting component is shown in Figura 5.43, “Twin Column Selection”.

Twin Column Selection with TwinColSelect160

User Interface Components

Page 163: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.43.Twin Column Selection

The setRows() method sets the height of the component by the number of visible items in theselection boxes. Setting the height with setHeight() to a defined value overrides the rowssetting.

CSS Style Rules

.v-select-twincol {} .v-select-twincol-options-caption {} .v-select-twincol-selections-caption {} .v-select-twincol-options {} .v-select-twincol-buttons {} .v-button {} .v-button-wrap {} .v-button-caption {} .v-select-twincol-deco {} .v-select-twincol-selections {}

The TwinColSelect component has an overall v-select-twincol style. If set, the left andright column captions have v-select-twincol-options-caption and v-select-twincol-options-caption style names, respectively.The left box, which displays the unselected items,has v-select-twincol-options-caption style and the right box, which displays the selecteditems, has v-select-twincol-options-selections style. Between them is the buttonarea, which has overall v-select-twincol-buttons style; the actual buttons reuse the stylesfor the Button component. Between the buttons is a divider element with v-select-twincol-deco style.

5.15.7. Allowing Adding New Items

Selection components can allow the user to add new items. Currently, only ComboBox allowsit, when the user types in a value and presses Enter. You need to enable the mode withsetNewItemsAllowed(true). Setting the component also in immediate mode may benecessary, as otherwise the item would not be added immediately when the user interacts withthe component, but after some other component causes a server request.

myselect.setNewItemsAllowed(true);myselect.setImmediate(true);

The user interface for adding new items depends on the selection component. The regularComboBox component allows you to simply type the new item in the combo box and hit Enterto add it.

Adding new items in not possible if the selection component is read-only or is bound to a Containerthat does not allow adding new items, and an attempt may result in an exception.

161Allowing Adding New Items

User Interface Components

Page 164: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Handling New Items

Adding new items is handled by a NewItemHandler, which gets the item caption string asparameter for the addNewItem() method.The default implementation, DefaultNewItemHandler,checks for read-only state, adds the item using the entered caption as the item ID, and if theselection component gets the captions from a property, copies the caption to that property. It alsoselects the item. The default implementation may not be suitable for all container types, in whichcase you need to define a custom handler. For example, a BeanItemContainer expects theitems to have the bean object itself as the ID, not a string.

// Have a bean container to put the beans infinal BeanItemContainer<Planet> container = new BeanItemContainer<Planet>(Planet.class);

// Put some example data in itcontainer.addItem(new Planet(1, "Mercury"));container.addItem(new Planet(2, "Venus"));container.addItem(new Planet(3, "Earth"));container.addItem(new Planet(4, "Mars"));

final ComboBox select = new ComboBox("Select or Add a Planet", container);select.setNullSelectionAllowed(false);

// Use the name property for item captionsselect.setItemCaptionPropertyId("name");

// Allow adding new itemsselect.setNewItemsAllowed(true);select.setImmediate(true);

// Custom handling for new itemsselect.setNewItemHandler(new NewItemHandler() { @Override public void addNewItem(String newItemCaption) { // Create a new bean - can't set all properties Planet newPlanet = new Planet(0, newItemCaption); container.addBean(newPlanet);

// Remember to set the selection to the new item select.select(newPlanet);

Notification.show("Added new planet called " + newItemCaption); }});

5.15.8. Multiple Selection

Some selection components, such as OptionGroup and ListSelect support a multiple selectionmode, which you can enable with setMultiSelect(). For TwinColSelect, which is especiallyintended for multiple selection, it is enabled by default.

myselect.setMultiSelect(true);

As in single selection mode, the property value of the component indicates the selection. Inmultiple selection mode, however, the property value is a Collection of the item IDs of the currently

Multiple Selection162

User Interface Components

Page 165: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

selected items.You can get and set the property with the getValue() and setValue() methodsas usual.

A change in the selection will trigger a ValueChangeEvent, which you can handle with aPropery.ValueChangeListener. As usual, you should use setImmediate(true) to triggerthe event immediately when the user changes the selection. The following example shows howto handle selection changes with a listener.

// A selection component with some itemsListSelect select = new ListSelect("My Selection");for (String planet: new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}) select.addItem(planet);

// Multiple selection modeselect.setMultiSelect(true);

// Feedback on value changesselect.addValueChangeListener( new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { // Some feedback layout.addComponent(new Label("Selected: " + event.getProperty().getValue().toString())); }});select.setImmediate(true);

5.15.9. Other Common Features

Item Icons

You can set an icon for each item with setItemIcon(), or define an item property that providesthe icon resource with setItemIconPropertyId(), in a fashion similar to captions. Notice,however, that icons are not supported in NativeSelect, TwinColSelect, and some other selectioncomponents and modes.This is because HTML does not support images inside the native selectelements. Icons are also not really visually applicable.

5.16. Table

Because of pressing release schedules to get this edition to your hands, we were unable tocompletely update this section. The description of the Table component should be mostly up-to-date, but some data binding related topics still require significant revision. Please consult theweb version once it is updated, or the next print edition.

The Table component is intended for presenting tabular data organized in rows and columns.The Table is one of the most versatile components in Vaadin. Table cells can include text orarbitrary UI components.You can easily implement editing of the table data, for example clickingon a cell could change it to a text field for editing.

The data contained in a Table is managed using the Data Model of Vaadin (see Capítulo 9,Binding Components to Data), through the Container interface of the Table. This makes itpossible to bind a table directly to a data source, such as a database query. Only the visible partof the table is loaded into the browser and moving the visible window with the scrollbar loadscontent from the server. While the data is being loaded, a tooltip will be displayed that shows the

163Other Common Features

User Interface Components

Page 166: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

current range and total number of items in the table. The rows of the table are items in thecontainer and the columns are properties. Each table row (item) is identified with an item identifier(IID), and each column (property) with a property identifier (PID).

When creating a table, you first need to define columns with addContainerProperty(). Thismethod comes in two flavors. The simpler one takes the property ID of the column and uses italso as the caption of the column. The more complex one allows differing PID and header for thecolumn. This may make, for example, internationalization of table headers easier, because if aPID is internationalized, the internationalization has to be used everywhere where the PID isused.The complex form of the method also allows defining an icon for the column from a resource.The "default value" parameter is used when new properties (columns) are added to the table, tofill in the missing values. (This default has no meaning in the usual case, such as below, wherewe add items after defining the properties.)

/* Create the table with a caption. */Table table = new Table("This is my Table");

/* Define the names and data types of columns. * The "default value" parameter is meaningless here. */table.addContainerProperty("First Name", String.class, null);table.addContainerProperty("Last Name", String.class, null);table.addContainerProperty("Year", Integer.class, null);

/* Add a few items in the table. */table.addItem(new Object[] { "Nicolaus","Copernicus",new Integer(1473)}, new Integer(1));table.addItem(new Object[] { "Tycho", "Brahe", new Integer(1546)}, new Integer(2));table.addItem(new Object[] { "Giordano","Bruno", new Integer(1548)}, new Integer(3));table.addItem(new Object[] { "Galileo", "Galilei", new Integer(1564)}, new Integer(4));table.addItem(new Object[] { "Johannes","Kepler", new Integer(1571)}, new Integer(5));table.addItem(new Object[] { "Isaac", "Newton", new Integer(1643)}, new Integer(6));

In this example, we used an increasing Integer object as the Item Identifier, given as the secondparameter to addItem(). The actual rows are given simply as object arrays, in the same orderin which the properties were added. The objects must be of the correct class, as defined in theaddContainerProperty() calls.

Figura 5.44. Basic Table Example

Scalability of the Table is largely dictated by the container. The default IndexedContainer isrelatively heavy and can cause scalability problems, for example, when updating the values. Use

Table164

User Interface Components

Page 167: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

of an optimized application-specific container is recommended. Table does not have a limit forthe number of items and is just as fast with hundreds of thousands of items as with just a few.With the current implementation of scrolling, there is a limit of around 500 000 rows, dependingon the browser and the pixel height of rows.

5.16.1. Selecting Items in a Table

The Table allows selecting one or more items by clicking them with the mouse. When the userselects an item, the IID of the item will be set as the property of the table and a ValueChangeEventis triggered. To enable selection, you need to set the table selectable. You will also need to setit as immediate in most cases, as we do below, because without it, the change in the propertywill not be communicated immediately to the server.

The following example shows how to enable the selection of items in a Table and how to handleValueChangeEvent events that are caused by changes in selection. You need to handle theevent with the valueChange() method of the Property.ValueChangeListener interface.

// Allow selecting items from the table.table.setSelectable(true);

// Send changes in selection immediately to server.table.setImmediate(true);

// Shows feedback from selection.final Label current = new Label("Selected: -");

// Handle selection change.table.addValueChangeListener(new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { current.setValue("Selected: " + table.getValue()); }});

Figura 5.45.Table Selection Example

If the user clicks on an already selected item, the selection will deselected and the table propertywill have null value. You can disable this behaviour by settingsetNullSelectionAllowed(false) for the table.

The selection is the value of the table's property, so you can get it with getValue(). You canget it also from a reference to the table itself. In single selection mode, the value is the itemidentifier of the selected item or null if no item is selected. In multiple selection mode (seebelow), the value is a Set of item identifiers. Notice that the set is unmodifiable, so you can notsimply change it to change the selection.

165Selecting Items in a Table

User Interface Components

Page 168: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Multiple Selection Mode

A table can also be in multiselect mode, where a user can select multiple items by clicking themwith left mouse button while holding the Ctrl key (or Meta key) pressed. If Ctrl is not held, clickingan item will select it and other selected items are deselected. The user can select a range byselecting an item, holding the Shift key pressed, and clicking another item, in which case all theitems between the two are also selected. Multiple ranges can be selected by first selecting arange, then selecting an item while holding Ctrl, and then selecting another item with both Ctrland Shift pressed.

The multiselect mode is enabled with the setMultiSelect() method of the AbstractSelectsuperclass of Table. Setting table in multiselect mode does not implicitly set it as selectable, soit must be set separately.

The setMultiSelectMode() property affects the control of multiple selection:MultiSelectMode.DEFAULT is the default behaviour, which requires holding the Ctrl (or Meta)key pressed while selecting items, while in MultiSelectMode.SIMPLE holding the Ctrl key isnot needed. In the simple mode, items can only be deselected by clicking them.

5.16.2.Table Features

Page Length and Scrollbar

The default style for Table provides a table with a scrollbar. The scrollbar is located at the rightside of the table and becomes visible when the number of items in the table exceeds the pagelength, that is, the number of visible items.You can set the page length with setPageLength().

Setting the page length to zero makes all the rows in a table visible, no matter how many rowsthere are. Notice that this also effectively disables buffering, as all the entire table is loaded tothe browser at once. Using such tables to generate reports does not scale up very well, as thereis some inevitable overhead in rendering a table with Ajax. For very large reports, generatingHTML directly is a more scalable solution.

Resizing Columns

You can set the width of a column programmatically from the server-side withsetColumnWidth().The column is identified by the property ID and the width is given in pixels.

The user can resize table columns by dragging the resize handle between two columns. Resizinga table column causes a ColumnResizeEvent, which you can handle with aTable.ColumnResizeListener. The table must be set in immediate mode if you want to receivethe resize events immediately, which is typical.

table.addColumnResizeListener(new Table.ColumnResizeListener(){ public void columnResize(ColumnResizeEvent event) { // Get the new width of the resized column int width = event.getCurrentWidth();

// Get the property ID of the resized column String column = (String) event.getPropertyId();

// Do something with the information table.setColumnFooter(column, String.valueOf(width) + "px"); }});

Table Features166

User Interface Components

Page 169: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Must be immediate to send the resize events immediatelytable.setImmediate(true);

See Figura 5.46, “Resizing Columns” for a result after the columns of a table has been resized.

Figura 5.46. Resizing Columns

Reordering Columns

If setColumnReorderingAllowed(true) is set, the user can reorder table columns bydragging them with the mouse from the column header,

Collapsing Columns

When setColumnCollapsingAllowed(true) is set, the right side of the table header showsa drop-down list that allows selecting which columns are shown. Collapsing columns is differentthan hiding columns with setVisibleColumns(), which hides the columns completely so thatthey can not be made visible (uncollapsed) from the user interface.

You can collapse columns programmatically with setColumnCollapsed(). Collapsing mustbe enabled before collapsing columns with the method or it will throw an IllegalAccessException.

// Allow the user to collapse and uncollapse columnstable.setColumnCollapsingAllowed(true);

// Collapse this column programmaticallytry { table.setColumnCollapsed("born", true);} catch (IllegalAccessException e) { // Can't occur - collapsing was allowed above System.err.println("Something horrible occurred");}

// Give enough width for the table to accommodate the// initially collapsed column latertable.setWidth("250px");

See Figura 5.47, “Collapsing Columns”.

Figura 5.47. Collapsing Columns

If the table has undefined width, it minimizes its width to fit the width of the visible columns. Ifsome columns are initially collapsed, the width of the table may not be enough to accomodate

167Table Features

User Interface Components

Page 170: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

them later, which will result in an ugly horizontal scrollbar. You should consider giving the tableenough width to accomodate columns uncollapsed by the user.

Components Inside a Table

The cells of a Table can contain any user interface components, not just strings. If the rows arehigher than the row height defined in the default theme, you have to define the proper row heightin a custom theme.

When handling events for components inside a Table, such as for the Button in the examplebelow, you usually need to know the item the component belongs to. Components do notthemselves know about the table or the specific item in which a component is contained.Therefore,the handling method must use some other means for finding out the Item ID of the item. Thereare a few possibilities. Usually the easiest way is to use the setData() method to attach anarbitrary object to a component. You can subclass the component and include the identityinformation there. You can also simply search the entire table for the item with the component,although that solution may not be so scalable.

The example below includes table rows with a Label in XHTML formatting mode, a multilineTextField, a CheckBox, and a Button that shows as a link.

// Create a table and add a style to allow setting the row height in theme.final Table table = new Table();table.addStyleName("components-inside");

/* Define the names and data types of columns. * The "default value" parameter is meaningless here. */table.addContainerProperty("Sum", Label.class, null);table.addContainerProperty("Is Transferred", CheckBox.class, null);table.addContainerProperty("Comments", TextField.class, null);table.addContainerProperty("Details", Button.class, null);

/* Add a few items in the table. */for (int i=0; i<100; i++) { // Create the fields for the current table row Label sumField = new Label(String.format( "Sum is <b>$%04.2f</b><br/><i>(VAT incl.)</i>", new Object[] {new Double(Math.random()*1000)}), Label.CONTENT_XHTML); CheckBox transferredField = new CheckBox("is transferred");

// Multiline text field. This required modifying the // height of the table row. TextField commentsField = new TextField(); commentsField.setRows(3);

// The Table item identifier for the row. Integer itemId = new Integer(i);

// Create a button and handle its click. A Button does not // know the item it is contained in, so we have to store the // item ID as user-defined data. Button detailsField = new Button("show details"); detailsField.setData(itemId); detailsField.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { // Get the item identifier from the user-defined data. Integer iid = (Integer)event.getButton().getData();

Table Features168

User Interface Components

Page 171: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Notification.show("Link " + iid.intValue() + " clicked."); } }); detailsField.addStyleName("link");

// Create the table row. table.addItem(new Object[] {sumField, transferredField, commentsField, detailsField}, itemId);}

// Show just three rows because they are so high.table.setPageLength(3);

The row height has to be set higher than the default with a style rule such as the following:

/* Table rows contain three-row TextField components. */.v-table-components-inside .v-table-cell-content { height: 54px;}

The table will look as shown in Figura 5.48, “Components in a Table”.

Figura 5.48. Components in a Table

Iterating Over a Table

As the items in a Table are not indexed, iterating over the items has to be done using an iterator.The getItemIds() method of the Container interface of Table returns a Collection of itemidentifiers over which you can iterate using an Iterator. For an example about iterating over aTable, please see Secção 9.5, “Collecting Items in Containers”. Notice that you may not modifythe Table during iteration, that is, add or remove items. Changing the data is allowed.

Filtering Table Contents

A table can be filtered if its container data source implements the Filterable interface, as thedefault IndexedContainer does. See Secção 9.5.7, “Filterable Containers”.

169Table Features

User Interface Components

Page 172: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.16.3. Editing the Values in a Table

Normally, a Table simply displays the items and their fields as text. If you want to allow the userto edit the values, you can either put them inside components as we did above, or you can simplycall setEditable(true) and the cells are automatically turned into editable fields.

Let us begin with a regular table with a some columns with usual Java types, namely a Date,Boolean, and a String.

// Create a table. It is by default not editable.final Table table = new Table();

// Define the names and data types of columns.table.addContainerProperty("Date", Date.class, null);table.addContainerProperty("Work", Boolean.class, null);table.addContainerProperty("Comments", String.class, null);

// Add a few items in the table.for (int i=0; i<100; i++) { Calendar calendar = new GregorianCalendar(2008,0,1); calendar.add(Calendar.DAY_OF_YEAR, i);

// Create the table row. table.addItem(new Object[] {calendar.getTime(), new Boolean(false), ""}, new Integer(i)); // Item identifier}

table.setPageLength(8);layout.addComponent(table);

You could put the table in editable mode right away if you need to. We'll continue the exampleby adding a mechanism to switch the Table from and to the editable mode.

final CheckBox switchEditable = new CheckBox("Editable");switchEditable.addValueChangeListener( new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { table.setEditable(((Boolean)event.getProperty() .getValue()).booleanValue()); }});switchEditable.setImmediate(true);layout.addComponent(switchEditable);

Now, when you check to checkbox, the components in the table turn into editable fields, as shownin Figura 5.49, “A Table in Normal and Editable Mode”.

Editing the Values in a Table170

User Interface Components

Page 173: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.49. A Table in Normal and Editable Mode

Field Factories

The field components that allow editing the values of particular types in a table are defined in afield factory that implements the TableFieldFactory interface. The default implementation isDefaultFieldFactory, which offers the following crude mappings:

Tabela 5.2.Type to Field Mappings in DefaultFieldFactory

Mapped to Field ClassProperty Type

A DateField.Date

A CheckBox.Boolean

A Form (deprecated in Vaadin 7). The fields ofthe form are automatically created from the

Item

item's properties using a FormFieldFactory.The normal use for this property type is insidea Form and is less useful inside a Table.

A TextField.The text field manages conversionsfrom the basic types, if possible.

other

Field factories are covered with more detail in Secção 9.4, “Creating Forms by Binding Fields toItems”. You could just implement the TableFieldFactory interface, but we recommend that youextend the DefaultFieldFactory according to your needs. In the default implementation, themappings are defined in the createFieldByPropertyType() method (you might want tolook at the source code) both for tables and forms.

Navigation in Editable Mode

In the editable mode, the editor fields can have focus. Pressing Tab moves the focus to nextcolumn or, at the last column, to the first column of the next item. Respectively, pressing Shift+Tabmoves the focus backward. If the focus is in the last column of the last visible item, the pressingTab moves the focus outside the table. Moving backward from the first column of the first itemmoves the focus to the table itself. Some updates to the table, such as changing the headers orfooters or regenerating a column, can move the focus from an editor component to the tableitself.

The default behaviour may be undesirable in many cases. For example, the focus also goesthrough any read-only editor fields and can move out of the table inappropriately.You can providebetter navigation is to use event handler for shortcut keys such as Tab, Arrow Up, Arrow Down,and Enter.

171Editing the Values in a Table

User Interface Components

Page 174: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Keyboard navigationclass KbdHandler implements Handler { Action tab_next = new ShortcutAction("Tab", ShortcutAction.KeyCode.TAB, null); Action tab_prev = new ShortcutAction("Shift+Tab", ShortcutAction.KeyCode.TAB, new int[] {ShortcutAction.ModifierKey.SHIFT}); Action cur_down = new ShortcutAction("Down", ShortcutAction.KeyCode.ARROW_DOWN, null); Action cur_up = new ShortcutAction("Up", ShortcutAction.KeyCode.ARROW_UP, null); Action enter = new ShortcutAction("Enter", ShortcutAction.KeyCode.ENTER, null); public Action[] getActions(Object target, Object sender) { return new Action[] {tab_next, tab_prev, cur_down, cur_up, enter}; }

public void handleAction(Action action, Object sender, Object target) { if (target instanceof TextField) { // Move according to keypress int itemid = (Integer) ((TextField) target).getData(); if (action == tab_next || action == cur_down) itemid++; else if (action == tab_prev || action == cur_up) itemid--; // On enter, just stay where you were. If we did // not catch the enter action, the focus would be // moved to wrong place.

if (itemid >= 0 && itemid < table.size()) { TextField newTF = valueFields.get(itemid); if (newTF != null) newTF.focus(); } } }}

// Panel that handles keyboard navigationPanel navigator = new Panel();navigator.addStyleName(Reindeer.PANEL_LIGHT);navigator.addComponent(table);navigator.addActionHandler(new KbdHandler());

The main issue in implementing keyboard navigation in an editable table is that the editor fieldsdo not know the table they are in.To find the parent table, you can either look up in the componentcontainer hierarchy or simply store a reference to the table with setData() in the field component.The other issue is that you can not acquire a reference to an editor field from the Table component.One solution is to use some external collection, such as a HashMap, to map item IDs to theeditor fields.

// Can't access the editable components from the table so// must store the informationfinal HashMap<Integer,TextField> valueFields = new HashMap<Integer,TextField>();

Editing the Values in a Table172

User Interface Components

Page 175: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The map has to be filled in a TableFieldFactory, such as in the following. You also need to setthe reference to the table there and you can also set the initial focus there.

table.setTableFieldFactory(new TableFieldFactory () { public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) { TextField field = new TextField((String) propertyId);

// User can only edit the numeric column if ("Source of Fear".equals(propertyId)) field.setReadOnly(true); else { // The numeric column // The field needs to know the item it is in field.setData(itemId);

// Remember the field valueFields.put((Integer) itemId, field);

// Focus the first editable value if (((Integer)itemId) == 0) field.focus(); } return field; }});

The issues are complicated by the fact that the editor fields are not generated for the entire table,but only for a cache window that includes the visible items and some items above and below it.For example, if the beginning of a big scrollable table is visible, the editor component for the lastitem does not exist. This issue is relevant mostly if you want to have wrap-around navigation thatjumps from the last to first item and vice versa.

5.16.4. Column Headers and Footers

Table supports both column headers and footers; the headers are enabled by default.

Headers

The table header displays the column headers at the top of the table. You can use the columnheaders to reorder or resize the columns, as described earlier. By default, the header of a columnis the property ID of the column, unless given explicitly with setColumnHeader().

// Define the propertiestable.addContainerProperty("lastname", String.class, null);table.addContainerProperty("born", Integer.class, null);table.addContainerProperty("died", Integer.class, null);

// Set nicer header namestable.setColumnHeader("lastname", "Name");table.setColumnHeader("born", "Born");table.setColumnHeader("died", "Died");

The text of the column headers and the visibility of the header depends on the column headermode. The header is visible by default, but you can disable it withsetColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN).

173Column Headers and Footers

User Interface Components

Page 176: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Footers

The table footer can be useful for displaying sums or averages of values in a column, and so on.The footer is not visible by default; you can enable it with setFooterVisible(true). Unlikein the header, the column headers are empty by default. You can set their value withsetColumnFooter(). The columns are identified by their property ID.

The following example shows how to calculate average of the values in a column:

// Have a table with a numeric columnTable table = new Table("Custom Table Footer");table.addContainerProperty("Name", String.class, null);table.addContainerProperty("Died At Age", Integer.class, null);

// Insert some dataObject people[][] = {{"Galileo", 77}, {"Monnier", 83}, {"Vaisala", 79}, {"Oterma", 86}};for (int i=0; i<people.length; i++) table.addItem(people[i], new Integer(i));

// Calculate the average of the numeric columndouble avgAge = 0;for (int i=0; i<people.length; i++) avgAge += (Integer) people[i][1];avgAge /= people.length;

// Set the footerstable.setFooterVisible(true);table.setColumnFooter("Name", "Average");table.setColumnFooter("Died At Age", String.valueOf(avgAge));

// Adjust the table height a bittable.setPageLength(table.size());

The resulting table is shown in Figura 5.50, “A Table with a Footer”.

Figura 5.50. A Table with a Footer

Handling Mouse Clicks on Headers and Footers

Normally, when the user clicks a column header, the table will be sorted by the column, assumingthat the data source is Sortable and sorting is not disabled. In some cases, you might want someother functionality when the user clicks the column header, such as selecting the column in someway.

Column Headers and Footers174

User Interface Components

Page 177: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Clicks in the header cause a HeaderClickEvent, which you can handle with aTable.HeaderClickListener. Click events on the table header (and footer) are, like button clicks,sent immediately to server, so there is no need to set setImmediate().

// Handle the header clickstable.addHeaderClickListener(new Table.HeaderClickListener() { public void headerClick(HeaderClickEvent event) { String column = (String) event.getPropertyId(); Notification.show("Clicked " + column + "with " + event.getButtonName()); }});

// Disable the default sorting behaviortable.setSortDisabled(true);

Setting a click handler does not automatically disable the sorting behavior of the header; youneed to disable it explicitly with setSortDisabled(true). Header click events are not sentwhen the user clicks the column resize handlers to drag them.

The HeaderClickEvent object provides the identity of the clicked column with getPropertyId().The getButton() reports the mouse button with which the click was made: BUTTON_LEFT,BUTTON_RIGHT, or BUTTON_MIDDLE.The getButtonName() a human-readable button namein English: "left", "right", or "middle". The isShiftKey(), isCtrlKey(), etc., methodsindicate if the Shift, Ctrl, Alt or other modifier keys were pressed during the click.

Clicks in the footer cause a FooterClickEvent, which you can handle with aTable.FooterClickListener. Footers do not have any default click behavior, like the sorting inthe header. Otherwise, handling clicks in the footer is equivalent to handling clicks in the header.

5.16.5. Generated Table Columns

You might want to have a column that has values calculated from other columns. Or you mightwant to format table columns in some way, for example if you have columns that display currencies.The ColumnGenerator interface allows defining custom generators for such columns.

You add new generated columns to a Table with addGeneratedColumn(). It takes the columnidentifier as its parameters. Usually you want to have a more user-friendly and possiblyinternationalized column header. You can set the header and a possible icon by callingaddContainerProperty() before adding the generated column.

// Define table columns. table.addContainerProperty( "date", Date.class, null, "Date", null, null);table.addContainerProperty( "quantity", Double.class, null, "Quantity (l)", null, null);table.addContainerProperty( "price", Double.class, null, "Price (e/l)", null, null);table.addContainerProperty( "total", Double.class, null, "Total (e)", null, null);

// Define the generated columns and their generators.table.addGeneratedColumn("date", new DateColumnGenerator());table.addGeneratedColumn("quantity", new ValueColumnGenerator("%.2f l"));table.addGeneratedColumn("price",

175Generated Table Columns

User Interface Components

Page 178: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

new PriceColumnGenerator());table.addGeneratedColumn("total", new ValueColumnGenerator("%.2f e"));

Notice that the addGeneratedColumn() always places the generated columns as the lastcolumn, even if you defined some other order previously. You will have to set the proper orderwith setVisibleColumns().

table.setVisibleColumns(new Object[] {"date", "quantity", "price", "total"});

The generators are objects that implement the Table.ColumnGenerator interface and itsgenerateCell() method.The method gets the identity of the item and column as its parameters,in addition to the table object. It has to return a component object.

The following example defines a generator for formatting Double valued fields according to aformat string (as in java.util.Formatter).

/** Formats the value in a column containing Double objects. */class ValueColumnGenerator implements Table.ColumnGenerator { String format; /* Format string for the Double values. */

/** * Creates double value column formatter with the given * format string. */ public ValueColumnGenerator(String format) { this.format = format; }

/** * Generates the cell containing the Double value. * The column is irrelevant in this use case. */ public Component generateCell(Table source, Object itemId, Object columnId) { // Get the object stored in the cell as a property Property prop = source.getItem(itemId).getItemProperty(columnId); if (prop.getType().equals(Double.class)) { Label label = new Label(String.format(format, new Object[] { (Double) prop.getValue() }));

// Set styles for the column: one indicating that it's // a value and a more specific one with the column // name in it. This assumes that the column name // is proper for CSS. label.addStyleName("column-type-value"); label.addStyleName("column-" + (String) columnId); return label; } return null; }}

The generator is called for all the visible (or more accurately cached) items in a table. If the userscrolls the table to another position in the table, the columns of the new visible rows are generateddynamically. The columns in the visible (cached) rows are also generated always when an itemhas a value change. It is therefore usually safe to calculate the value of generated cells from thevalues of different rows (items).

Generated Table Columns176

User Interface Components

Page 179: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

When you set a table as editable, regular fields will change to editing fields. When the userchanges the values in the fields, the generated columns will be updated automatically. Putting atable with generated columns in editable mode has a few quirks. The editable mode of Tabledoes not affect generated columns. You have two alternatives: either you generate the editingfields in the generator or, in case of formatter generators, remove the generator in the editablemode. The example below uses the latter approach.

// Have a check box that allows the user// to make the quantity and total columns editable.final CheckBox editable = new CheckBox( "Edit the input values - calculated columns are regenerated");

editable.setImmediate(true);editable.addClickListener(new ClickListener() { public void buttonClick(ClickEvent event) { table.setEditable(editable.booleanValue());

// The columns may not be generated when we want to // have them editable. if (editable.booleanValue()) { table.removeGeneratedColumn("quantity"); table.removeGeneratedColumn("total"); } else { // Not editable // Show the formatted values. table.addGeneratedColumn("quantity", new ValueColumnGenerator("%.2f l")); table.addGeneratedColumn("total", new ValueColumnGenerator("%.2f e")); } // The visible columns are affected by removal // and addition of generated columns so we have // to redefine them. table.setVisibleColumns(new Object[] {"date", "quantity", "price", "total", "consumption", "dailycost"}); }});

You will also have to set the editing fields in immediate mode to have the update occurimmediately when an edit field loses the focus. You can set the fields in immediate mode withthe a custom TableFieldFactory, such as the one given below, that just extends the defaultimplementation to set the mode:

public class ImmediateFieldFactory extends DefaultFieldFactory { public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) { // Let the DefaultFieldFactory create the fields... Field field = super.createField(container, itemId, propertyId, uiContext);

// ...and just set them as immediate. ((AbstractField)field).setImmediate(true);

return field; }}...table.setTableFieldFactory(new ImmediateFieldFactory());

177Generated Table Columns

User Interface Components

Page 180: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

If you generate the editing fields with the column generator, you avoid having to use such a fieldfactory, but of course have to generate the fields for both normal and editable modes.

Figura 5.51, “Table with Generated Columns in Normal and Editable Mode” shows a table withcolumns calculated (blue) and simply formatted (black) with column generators.

Figura 5.51.Table with Generated Columns in Normal and Editable Mode

5.16.6. Formatting Table Columns

The displayed values of properties shown in a table are normally formatted using the toString()method of each property. Customizing the format of a column can be done in several ways:

• Using ColumnGenerator to generate a second column that is formatted. The originalcolumn needs to be set invisible. See Secção 5.16.5, “Generated Table Columns”.

• Using a PropertyFormatter as a proxy between the table and the data property. Thisalso normally requires using an mediate container in the table.

• Overriding the default formatPropertyValue() in Table.

As using a PropertyFormatter is generally much more awkward than overriding theformatPropertyValue(), its use is not described here.

You can override formatPropertyValue() as is done in the following example:

// Create a table that overrides the default// property (column) formatfinal Table table = new Table("Formatted Table") { @Override protected String formatPropertyValue(Object rowId,

Formatting Table Columns178

User Interface Components

Page 181: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Object colId, Property property) { // Format by property type if (property.getType() == Date.class) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return df.format((Date)property.getValue()); }

return super.formatPropertyValue(rowId, colId, property); }};

// The table has some columnstable.addContainerProperty("Time", Date.class, null);

... Fill the table with data ...

You can also distinguish between columns by the colId parameter, which is the property ID ofthe column. DecimalFormat is useful for formatting decimal values.

... in formatPropertyValue() ...} else if ("Value".equals(pid)) { // Format a decimal value for a specific locale DecimalFormat df = new DecimalFormat("#.00", new DecimalFormatSymbols(locale)); return df.format((Double) property.getValue());}...table.addContainerProperty("Value", Double.class, null);

A table with the formatted date and decimal value columns is shown in Figura 5.52, “FormattedTable Columns”.

Figura 5.52. Formatted Table Columns

You can use CSS for further styling of table rows, columns, and individual cells by using aCellStyleGenerator. It is described in Secção 5.16.7, “CSS Style Rules”.

5.16.7. CSS Style Rules

Styling the overall style of a Table can be done with the following CSS rules.

.v-table {} .v-table-header-wrap {} .v-table-header {} .v-table-header-cell {} .v-table-resizer {} /* Column resizer handle. */ .v-table-caption-container {}

179CSS Style Rules

User Interface Components

Page 182: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

.v-table-body {} .v-table-row-spacer {} .v-table-table {} .v-table-row {} .v-table-cell-content {}

Notice that some of the widths and heights in a table are calculated dynamically and can not beset in CSS.

Setting Individual Cell Styles

The Table.CellStyleGenerator interface allows you to set the CSS style for each individual cellin a table. You need to implement the getStyle(), which gets the row (item) and column(property) identifiers as parameters and can return a style name for the cell. The returned stylename will be concatenated to prefix "v-table-cell-content-".

The getStyle() is called also for each row, so that the propertyId parameter is null. Thisallows setting a row style.

Alternatively, you can use a Table.ColumnGenerator (see Secção 5.16.5, “Generated TableColumns”) to generate the actual UI components of the cells and add style names to them.

Table table = new Table("Table with Cell Styles");table.addStyleName("checkerboard");

// Add some columns in the table. In this example, the property// IDs of the container are integers so we can determine the// column number easily.table.addContainerProperty("0", String.class, null, "", null, null);for (int i=0; i<8; i++) table.addContainerProperty(""+(i+1), String.class, null, String.valueOf((char) (65+i)), null, null);

// Add some items in the table.table.addItem(new Object[]{ "1", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(0));table.addItem(new Object[]{ "2", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(1));for (int i=2; i<6; i++) table.addItem(new Object[]{String.valueOf(i+1), "", "", "", "", "", "", "", ""}, new Integer(i));table.addItem(new Object[]{ "7", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(6));table.addItem(new Object[]{ "8", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(7));table.setPageLength(8);

// Set cell style generatortable.setCellStyleGenerator(new Table.CellStyleGenerator() { public String getStyle(Object itemId, Object propertyId) { // Row style setting, not relevant in this example. if (propertyId == null) return "green"; // Will not actually be visible

int row = ((Integer)itemId).intValue(); int col = Integer.parseInt((String)propertyId);

// The first column. if (col == 0)

CSS Style Rules180

User Interface Components

Page 183: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

return "rowheader";

// Other cells. if ((row+col)%2 == 0) return "black"; else return "white"; }});

You can then style the cells, for example, as follows:

/* Center the text in header. */.v-table-header-cell { text-align: center;}

/* Basic style for all cells. */.v-table-checkerboard .v-table-cell-content { text-align: center; vertical-align: middle; padding-top: 12px; width: 20px; height: 28px;}

/* Style specifically for the row header cells. */.v-table-cell-content-rowheader { background: #E7EDF3 url(../default/table/img/header-bg.png) repeat-x scroll 0 0;}

/* Style specifically for the "white" cells. */.v-table-cell-content-white { background: white; color: black;}

/* Style specifically for the "black" cells. */.v-table-cell-content-black { background: black; color: white;}

The table will look as shown in Figura 5.53, “Cell Style Generator for a Table”.

181CSS Style Rules

User Interface Components

Page 184: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.53. Cell Style Generator for a Table

5.17. Tree

The Tree component allows a natural way to represent data that has hierarchical relationships,such as filesystems or message threads. The Tree component in Vaadin works much like thetree components of most modern desktop user interface toolkits, for example in directory browsing.

The typical use of the Tree component is for displaying a hierachical menu, like a menu on theleft side of the screen, as in Figura 5.54, “A Tree Component as a Menu”, or for displayingfilesystems or other hierarchical datasets. The menu style makes the appearance of the treemore suitable for this purpose.

final Object[][] planets = new Object[][]{ new Object[]{"Mercury"}, new Object[]{"Venus"}, new Object[]{"Earth", "The Moon"}, new Object[]{"Mars", "Phobos", "Deimos"}, new Object[]{"Jupiter", "Io", "Europa", "Ganymedes", "Callisto"}, new Object[]{"Saturn", "Titan", "Tethys", "Dione", "Rhea", "Iapetus"}, new Object[]{"Uranus", "Miranda", "Ariel", "Umbriel", "Titania", "Oberon"}, new Object[]{"Neptune", "Triton", "Proteus", "Nereid", "Larissa"}};

Tree tree = new Tree("The Planets and Major Moons");

/* Add planets as root items in the tree. */for (int i=0; i<planets.length; i++) { String planet = (String) (planets[i][0]); tree.addItem(planet);

if (planets[i].length == 1) { // The planet has no moons so make it a leaf. tree.setChildrenAllowed(planet, false); } else { // Add children (moons) under the planets. for (int j=1; j<planets[i].length; j++) { String moon = (String) planets[i][j];

Tree182

User Interface Components

Page 185: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Add the item as a regular item. tree.addItem(moon);

// Set it to be a child. tree.setParent(moon, planet);

// Make the moons look like leaves. tree.setChildrenAllowed(moon, false); }

// Expand the subtree. tree.expandItemsRecursively(planet); }}

main.addComponent(tree);

Figura 5.54, “A Tree Component as a Menu” below shows the tree from the code example in apractical situation.

You can read or set the currently selected item by the value property of the Tree component,that is, with getValue() and setValue(). When the user clicks an item on a tree, the tree willreceive an ValueChangeEvent, which you can catch with a ValueChangeListener. To receivethe event immediately after the click, you need to set the tree as setImmediate(true).

The Tree component uses Container data sources much like the Table component, with theaddition that it also utilizes hierarchy information maintained by a HierarchicalContainer. Thecontained items can be of any item type supported by the container. The default container andits addItem() assume that the items are strings and the string value is used as the item ID.

5.18. MenuBar

The MenuBar component allows creating horizontal dropdown menus, much like the main menuin desktop applications.

Figura 5.55. Menu Bar

5.18.1. Creating a Menu

The actual menu bar component is first created as follows:

MenuBar menubar = new MenuBar();main.addComponent(menubar);

183MenuBar

User Interface Components

Page 186: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.54. A Tree Component as a Menu

You insert the top-level menu items to the MenuBar object with the addItem() method. It takesa string label, an icon resource, and a command as its parameters. The icon and command arenot required and can be null. The addItem() method returns a MenuBar.MenuItem object,which you can use to add sub-menu items.The MenuItem has an identical addItem() method.

For example (the command is explained later):

// A top-level menu item that opens a submenuMenuItem drinks = barmenu.addItem("Beverages", null, null);

// Submenu item with a sub-submenuMenuItem hots = drinks.addItem("Hot", null, null);hots.addItem("Tea", new ThemeResource("icons/tea-16px.png"), mycommand);hots.addItem("Coffee", new ThemeResource("icons/coffee-16px.png"), mycommand);

// Another submenu item with a sub-submenuMenuItem colds = drinks.addItem("Cold", null, null);colds.addItem("Milk", null, mycommand);colds.addItem("Weissbier", null, mycommand);

// Another top-level itemMenuItem snacks = barmenu.addItem("Snacks", null, null);snacks.addItem("Weisswurst", null, mycommand);snacks.addItem("Bratwurst", null, mycommand);snacks.addItem("Currywurst", null, mycommand);

// Yet another top-level itemMenuItem servs = barmenu.addItem("Services", null, null);servs.addItem("Car Service", null, mycommand);

5.18.2. Handling Menu Selection

Menu selection is handled by executing a command when the user selects an item from themenu. A command is a call-back class that implements the MenuBar.Command interface.

// A feedback componentfinal Label selection = new Label("-");main.addComponent(selection);

Handling Menu Selection184

User Interface Components

Page 187: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Define a common menu command for all the menu items.MenuBar.Command mycommand = new MenuBar.Command() { public void menuSelected(MenuItem selectedItem) { selection.setValue("Ordered a " + selectedItem.getText() + " from menu."); } };

5.18.3. Menu Items

Menu items have properties such as a caption, icon, enabled, visible, and description (tooltip).The meaning of these is the same as for components.

Submenus are created by adding sub-items to an item with addItem() or addItemBefore().

The command property is a MenuBar.Command that is called when the particular menu itemis selected. The menuSelected() callback gets the clicked menu item as its parameter.

Menus can have separators, which are defined before or after an item withaddSeparatorBefore() or addSeparator() on the item, respectively.

MenuItem drinks = barmenu.addItem("Beverages", null, null);...

// A sub-menu item after a separatordrinks.addSeparator();drinks.addItem("Quit Drinking", null, null);

Enabling checkable on an menu item with setCheckable() allows the user to switch betweenchecked and unchecked state by clicking on the item. You can set the checked state withsetChecked(). Note that if such an item has a command, the checked state is not flippedautomatically, but you need to do it explicitly.

Menu items have various other properties as well, see the API documentation for more details.

5.18.4. CSS Style Rules

.v-menubar { } .v-menubar-submenu { } .v-menubar-menuitem { } .v-menubar-menuitem-caption { } .v-menubar-menuitem-selected { } .v-menubar-submenu-indicator { }

The menu bar has the overall style name .v-menubar. Each menu item has .v-menubar-menuitem style normally and additionally .v-menubar-selected when the item is selected,that is, when the mouse pointer hovers over it. The item caption is inside a v-menubar-menuitem-caption. In the top-level menu bar, the items are directly under the componentelement.

Submenus are floating v-menubar-submenu elements outside the menu bar element.Therefore,you should not try to match on the component element for the submenu popups. In submenus,any further submenu levels are indicated with a v-menubar-submenu-indicator.

185Menu Items

User Interface Components

Page 188: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

1. Styling Menu Items

You can set the CSS style name for the menu items with setStyleName(), just like forcomponents. The style name will be prepended with v-menubar-menuitem-. As MenuBardoes not indicate the previous selection in any way, you can do that by highlighting the previouslyselected item. However, beware that the selected style for menu items, that is, v-menubar-menuitem-selected, is reserved for mouse-hover indication.

MenuBar barmenu = new MenuBar();barmenu.addStyleName("mybarmenu");layout.addComponent(barmenu);

// A feedback componentfinal Label selection = new Label("-");layout.addComponent(selection);

// Define a common menu command for all the menu itemsMenuBar.Command mycommand = new MenuBar.Command() { MenuItem previous = null;

public void menuSelected(MenuItem selectedItem) { selection.setValue("Ordered a " + selectedItem.getText() + " from menu.");

if (previous != null) previous.setStyleName(null); selectedItem.setStyleName("highlight"); previous = selectedItem; } };

// Put some items in the menubarmenu.addItem("Beverages", null, mycommand);barmenu.addItem("Snacks", null, mycommand);barmenu.addItem("Services", null, mycommand);

You could then style the highlighting in CSS as follows:

.mybarmenu .v-menubar-menuitem-highlight { background: #000040; /* Dark blue */}

5.19. Embedded Resources

You can embed images in Vaadin UIs with the Image component, Adobe Flash graphics withFlash, and other web content with BrowserFrame.There is also a generic Embedded componentfor embedding other object types.The embedded content is referenced as resources, as describedin Secção 4.4, “Imagens e Outros Recursos”.

The following example displays an image as a class resource loaded with the class loader:

Image image = new Image("Yes, logo:", new ClassResource("vaadin-logo.png"));main.addComponent(image);

Styling Menu Items186

User Interface Components

Page 189: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The caption can be given as null to disable it. An empty string displays an empty caption whichtakes a bit space. The caption is managed by the containing layout.

You can set an altenative text for an embedded resource with setAlternateText(), whichcan be shown if images are disabled in the browser for some reason. The text can be used foraccessibility purposes, such as for text-to-speech generation.

5.19.1. Embedded Image

The Image component allows embedding an image resource in a Vaadin UI.

// Serve the image from the themeResource res = new ThemeResource("img/myimage.png");

// Display the image without captionImage image = new Image(null, res);layout.addComponent(image);

The Image component has by default undefined size in both directions, so it will automaticallyfit the size of the embedded image. If you want scrolling with scroll bars, you can put the imageinside a Panel that has a defined size to enable scrolling, as described in Secção 6.6.1, “Scrollingthe Panel Content”. You can also put it inside some other component container and set theoverflow: auto CSS property for the container element in a theme to enable automaticscrollbars.

Generating and Reloading Images

You can also generate the image content dynamically using a StreamResource, as describedin Secção 4.4.5, “Recursos de Stream”, or with a RequestHandler.

If the image changes, the browser needs to reload it. Simply updating the stream resource is notenough. Because of how caching is handled in some browsers, you can cause a reload easiestby renaming the filename of the resource with a unique name, such as one including a timestamp.You should set cache time to zero with setCacheTime() for the resource object when youcreate it.

// Create the stream resource with some initial filenameStreamResource imageResource = new StreamResource(imageSource, "initial-filename.png");

// Instruct browser not to cache the imageimageResource.setCacheTime(0);

// Display the imageImage image = new Image(null, imageResource);

When refreshing, you also need to call markAsDirty() for the Image object.

// This needs to be done, but is not sufficientimage.markAsDirty();

// Generate a filename with a timestampSimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");String filename = "myfilename-" + df.format(new Date()) + ".png";

// Replace the filename in the resourceimageResource.setFilename(makeImageFilename());

187Embedded Image

User Interface Components

Page 190: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.19.2. Adobe Flash Graphics

The Flash component allows embedding Adobe Flash animations in Vaadin UIs.

Flash flash = new Flash(null, new ThemeResource("img/vaadin_spin.swf"));layout.addComponent(flash);

You can set Flash parameters with setParameter(), which takes a parameter's name andvalue as strings. You can also set the codeBase, archive, and standBy attributes for theFlash object element in HTML.

5.19.3. BrowserFrame

The BrowserFrame allows embedding web content inside an HTML <iframe> element. Youcan refer to an external URL with ExternalResource.

As the BrowserFrame has undefined size by default, it is critical that you define a meaningfulsize for it, either fixed or relative.

BrowserFrame browser = new BrowserFrame("Browser", new ExternalResource("http://demo.vaadin.com/sampler/"));browser.setWidth("600px");browser.setHeight("400px");layout.addComponent(browser);

Notice that web pages can prevent embedding them in an <iframe>.

5.19.4. Generic Embedded Objects

The generic Embedded component allows embedding all sorts of objects, such as SVG graphics,Java applets, and PDF documents, in addition to the images, Flash graphics, and browser frameswhich you can embed with the specialized components.

For example, to display a Flash animation:

// A resource reference to some objectResource res = new ThemeResource("img/vaadin_spin.swf");

// Display the objectEmbedded object = new Embedded("My Object", res);layout.addComponent(object);

Or an SVG image:

// A resource reference to some objectResource res = new ThemeResource("img/reindeer.svg");

// Display the objectEmbedded object = new Embedded("My SVG", res);object.setMimeType("image/svg+xml"); // Unnecessarylayout.addComponent(object);

The MIME type of the objects is usually detected automatically from the filename extension withthe FileTypeResolver utility in Vaadin. If not, you can set it explicitly with setMimeType(), aswas done in the example above (where it was actually unnecessary).

Adobe Flash Graphics188

User Interface Components

Page 191: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Some embeddable object types may require special support in the browser. You should makesure that there is a proper fallback mechanism if the browser does not support the embeddedtype.

5.20. Upload

The Upload component allows a user to upload files to the server. It displays a file name entrybox, a file selection button, and an upload submit button. The user can either write the filenamein the text area or click the Browse button to select a file. After the file is selected, the user sendsthe file by clicking the upload submit button.

Uploading requires a receiver that implements Upload.Receiver to provide an output streamto which the upload is written by the server.

Upload upload = new Upload("Upload it here", receiver);

Figura 5.56. Upload Component

You can set the text of the upload button with setButtonCaption(). Note that it is difficult tochange the caption or look of the Browse button. This is a security feature of web browsers. Thelanguage of the Browse button is determined by the browser, so if you wish to have the languageof the Upload component consistent, you will have to use the same language in your application.

upload.setButtonCaption("Upload Now");

You can also hide the upload button with .v-upload .v-button {display: none} intheme, have custom logic for starting the upload, and call startUpload() to start it. If theupload component has setImmediate(true) enabled, uploading starts immediately afterchoosing the file.

5.20.1. Receiving Upload Data

The uploaded files are typically stored as files in a file system, in a database, or as temporaryobjects in memory.The upload component writes the received data to an java.io.OutputStreamso you have plenty of freedom in how you can process the upload content.

To use the Upload component, you need to implement the Upload.Receiver interface. ThereceiveUpload() method of the receiver is called when the user clicks the submit button.Themethod must return an OutputStream. To do this, it typically creates a file or a memory bufferto which the stream is written. The method gets the file name and MIME type of the file, asreported by the browser.

While uploading, the upload progress can be monitored with an Upload.ProgressListener.The updateProgress() method gets the number of read bytes and the content length asparameters. The content length is reported by the browser, is not reliable, and may be -1 ifunknown. It is therefore recommended to follow the upload progress and check the allowed sizein a progress listener. Upload can be terminated by calling interruptUpload() on the uploadcomponent.You may want to use a ProgressBar to visualize the progress, and in indeterminatemode if the content length is not known.

189Upload

User Interface Components

Page 192: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

When an upload is finished, successfully or unsuccessfully, the Upload component will emit theUpload.FinishedEvent event, which you can handle with an Upload.FinishedListener addedto the upload component.The event object will include the file name, MIME type, and final lengthof the file. More specific Upload.FailedEvent and Upload.SucceededEvent events will be calledin the cases where the upload failed or succeeded, respectively.

The following example uploads images to /tmp/uploads directory in (UNIX) filesystem (thedirectory must exist or the upload fails).The component displays the uploaded image in an Imagecomponent.

// Show uploaded file in this placeholderfinal Embedded image = new Embedded("Uploaded Image");image.setVisible(false);

// Implement both receiver that saves upload in a file and// listener for successful uploadclass ImageUploader implements Receiver, SucceededListener { public File file;

public OutputStream receiveUpload(String filename, String mimeType) { // Create upload stream FileOutputStream fos = null; // Stream to write to try { // Open the file for writing. file = new File("/tmp/uploads/" + filename); fos = new FileOutputStream(file); } catch (final java.io.FileNotFoundException e) { new Notification("Could not open file<br/>", e.getMessage(), Notification.Type.ERROR_MESSAGE) .show(Page.getCurrent()); return null; } return fos; // Return the output stream to write to }

public void uploadSucceeded(SucceededEvent event) { // Show the uploaded file in the image viewer image.setVisible(true); image.setSource(new FileResource(file)); }};ImageUploader receiver = new ImageUploader();

// Create the upload with a caption and set receiver laterUpload upload = new Upload("Upload Image Here", receiver);upload.setButtonCaption("Start Upload");upload.addSucceededListener(receiver);

// Put the components in a panelPanel panel = new Panel("Cool Image Storage");Layout panelContent = new VerticalLayout();panelContent.addComponents(upload, image);panel.setContent(panelContent);

Note that the example does not check the type of the uploaded files in any way, which will causean error if the content is anything else but an image. The program also assumes that the MIME

Receiving Upload Data190

User Interface Components

Page 193: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

type of the file is resolved correctly based on the file name extension. After uploading an image,the component will look as shown in Figura 5.57, “Image Upload Example”.

Figura 5.57. Image Upload Example

5.20.2. CSS Style Rules

.v-upload { } .gwt-FileUpload { } .v-button { } .v-button-wrap { } .v-button-caption { }

The Upload component has an overall v-upload style.The upload button has the same structureand style as a regular Button component.

5.21. ProgressBar

The ProgressBar component allows displaying the progress of a task graphically. The progressis specified as a floating-point value between 0.0 and 1.0.

Figura 5.58.The Progress Bar Component

191CSS Style Rules

User Interface Components

Page 194: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

To display upload progress with the Upload component, you can update the progress bar in aProgressListener.

When the position of a progress bar is done in a background thread, the change is not shown inthe browser immediately. You need to use either polling or server push to update the browser.You can enable polling with setPollInterval() in the current UI instance. See Secção 11.16,“Server Push” for instructions about using server push. Whichever method you use to update theUI, it is important to lock the user session by modifying the progress bar value inside access()call, as illustrated in the following example and described in Secção 11.16.3, “Accessing UI fromAnother Thread”.

final ProgressBar bar = new ProgressBar(0.0f);layout.addComponent(bar);

layout.addComponent(new Button("Increase", new ClickListener() { @Override public void buttonClick(ClickEvent event) { float current = bar.getValue(); if (current < 1.0f) bar.setValue(current + 0.10f); }}));

5.21.1. Indeterminate Mode

In the indeterminate mode, a non-progressive indicator is displayed continuously. Theindeterminate indicator is a circular wheel in the built-in themes. The progress value has nomeaning in the indeterminate mode.

ProgressBar bar = new ProgressBar();bar.setIndeterminate(true);

Figura 5.59. Indeterminate Progress Bar

5.21.2. Doing Heavy Computation

The progress indicator is often used to display the progress of a heavy server-side computationtask, often running in a background thread. The UI, including the progress bar, can be updatedeither with polling or by using server push. When doing so, you must ensure thread-safety, mosteasily by updating the UI inside a UI.access() call in a Runnable, as described inSecção 11.16.3, “Accessing UI from Another Thread”.

In the following example, we create a thread in the server to do some "heavy work" and usepolling to update the UI. All the thread needs to do is to set the value of the progress bar withsetValue() and the current progress is displayed automatically when the browser polls theserver.

HorizontalLayout barbar = new HorizontalLayout();layout.addComponent(barbar);

Indeterminate Mode192

User Interface Components

Page 195: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Create the indicator, disabled until progress is startedfinal ProgressBar progress = new ProgressBar(new Float(0.0));progress.setEnabled(false);barbar.addComponent(progress);

final Label status = new Label("not running");barbar.addComponent(status);

// A button to start progressfinal Button button = new Button("Click to start");layout.addComponent(button);

// A thread to do some workclass WorkThread extends Thread { // Volatile because read in another thread in access() volatile double current = 0.0;

@Override public void run() { // Count up until 1.0 is reached while (current < 1.0) { current += 0.01;

// Do some "heavy work" try { sleep(50); // Sleep for 50 milliseconds } catch (InterruptedException e) {}

// Update the UI thread-safely UI.getCurrent().access(new Runnable() { @Override public void run() { progress.setValue(new Float(current)); if (current < 1.0) status.setValue("" + ((int)(current*100)) + "% done"); else status.setValue("all done"); } }); }

// Show the "all done" for a while try { sleep(2000); // Sleep for 2 seconds } catch (InterruptedException e) {}

// Update the UI thread-safely UI.getCurrent().access(new Runnable() { @Override public void run() { // Restore the state to initial progress.setValue(new Float(0.0)); progress.setEnabled(false);

// Stop polling UI.getCurrent().setPollInterval(-1);

button.setEnabled(true); status.setValue("not running");

193Doing Heavy Computation

User Interface Components

Page 196: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

} }); }}

// Clicking the button creates and runs a work threadbutton.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { final WorkThread thread = new WorkThread(); thread.start();

// Enable polling and set frequency to 0.5 seconds UI.getCurrent().setPollInterval(500);

// Disable the button until the work is done progress.setEnabled(true); button.setEnabled(false);

status.setValue("running..."); }});

The example is illustrated in Figura 5.60, “Doing Heavy Work”.

Figura 5.60. Doing Heavy Work

5.21.3. CSS Style Rules

.v-progressbar, v-progressbar-indeterminate {} .v-progressbar-wrapper {} .v-progressbar-indicator {}

The progress bar has a v-progressbar base style. The animation is the background of theelement with v-progressbar-wrapper style, by default an animated GIF image.The progressis an element with v-progressbar-indicator style inside the wrapper, and therefore displayedon top of it. When the progress element grows, it covers more and more of the animatedbackground.

In the indeterminate mode, the top element also has the v-progressbar-indeterminatestyle. The built-in themes simply display the animated GIF in the top element and have the innerelements disabled.

5.22. Slider

The Slider is a vertical or horizontal bar that allows setting a numeric value within a defined rangeby dragging a bar handle with the mouse. The value is shown when dragging the handle.

Slider has a number of different constructors that take a combination of the caption, minimumand maximum value, resolution, and the orientation of the slider.

CSS Style Rules194

User Interface Components

Page 197: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Create a vertical sliderfinal Slider vertslider = new Slider(1, 100);vertslider.setOrientation(SliderOrientation.VERTICAL);

Slider Properties

minMinimum value of the slider range. The default is 0.0.

maxMaximum value of the slider range. The default is 100.0.

resolutionThe number of digits after the decimal point. The default is 0.

orientationThe orientation can be either horizontal (SliderOrientation.HORIZONTAL) orvertical (SliderOrientation.VERTICAL). The default is horizontal.

As the Slider is a field component, you can handle value changes with a ValueChangeListener.The value of the Slider field is a Double object.

// Shows the value of the vertical sliderfinal Label vertvalue = new Label();vertvalue.setSizeUndefined();

// Handle changes in slider value.vertslider.addValueChangeListener( new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { double value = (Double) vertslider.getValue();

// Use the value box.setHeight((float) value, Sizeable.UNITS_PERCENTAGE); vertvalue.setValue(String.valueOf(value)); }});

// The slider has to be immediate to send the changes// immediately after the user drags the handle.vertslider.setImmediate(true);

You can set the value with the setValue() method defined in Slider that takes the value as anative double value. The setter can throw a ValueOutOfBoundsException, which you musthandle.

// Set the initial value. This has to be set after the// listener is added if we want the listener to handle// also this value change.try { vertslider.setValue(50.0);} catch (ValueOutOfBoundsException e) {}

Alternatively, you can use the regular setValue(Object), which does not do bounds checking.

Figura 5.61, “The Slider Component” shows both vertical (from the code examples) and horizontalsliders that control the size of a box. The slider values are displayed also in separate labels.

195Slider

User Interface Components

Page 198: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.61.The Slider Component

5.22.1. CSS Style Rules

.v-slider {}

.v-slider-base {}

.v-slider-handle {}

The enclosing style for the Slider is v-slider. The slider bar has style v-slider-base. Eventhough the handle is higher (for horizontal slider) or wider (for vertical slider) than the bar, thehandle element is nevertheless contained within the slider bar element. The appearance of thehandle comes from a background image defined in the background CSS property.

5.23. Calendar

The Calendar component allows organizing and displaying calendar events. The main featuresof the calendar include:

• Monthly, weekly, and daily views

• Two types of events: all-day events and events with a time range

• Add events directly, from a Container, or with an event provider

• Control the range of the visible dates

• Selecting and editing date or time range by dragging

• Drag and drop events to calendar

• Support for localization and timezones

User interaction with the calendar elements, such as date and week captions as well as events,is handled with event listeners. Also date/time range selections, event dragging, and event resizingcan be listened by the server. The weekly view has navigation buttons to navigate forward andbackward in time. These actions are also listened by the server. Custom navigation can beimplemented using event handlers, as described in Secção 5.23.10, “Customizing the Calendar”.

CSS Style Rules196

User Interface Components

Page 199: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The data source of a calendar can be practically anything, as its events are queried dynamicallyby the component.You can bind the calendar to a Vaadin container, or to any other data sourceby implementing an event provider.

The Calendar has undefined size by default and you usually want to give it a fixed or relativesize, for example as follows.

Calendar cal = new Calendar("My Calendar");cal.setWidth("600px");cal.setHeight("300px");

After creating the calendar, you need to set a time range for it, which also controls the view mode,and set up the data source for calendar events.

5.23.1. Date Range and View Mode

The Vaadin Calendar has two types of views that are shown depending on the date range of thecalendar. The weekly view displays a week by default. It can show anything between one toseven days a week, and is also used as a single-day view. The view mode is determined fromthe date range of the calendar, defined by a start and an end date. Calendar will be shown in amonthly view when the date range is over than one week (seven days) long. The date range isalways calculated in an accuracy of one millisecond.

The monthly view, shown in Figura 5.62, “Monthly view with All-Day and Normal Events”, caneasily be used to control all types of events, but it is best suited for events that last for one ormore days. You can drag the events to move them. In the figure, you can see two longer eventsthat are highlighted with a blue and green background color. Other markings are shorter dayevents that last less than a 24 hours. These events can not be moved by dragging in the monthlyview.

In Figura 5.63, “Weekly View”, you can see four normal day events and also all-day events atthe top of the time line grid.

In the following, we set the calendar to show only one day, which is the current day.

cal.setStartDate(new Date());cal.setEndDate(new Date());

Notice that although the range we set above is actually zero time long, the calendar still rendersthe time from 00:00 to 23:59. This is normal, as the Vaadin Calendar is guaranteed to render atleast the date range provided, but may expand it. This behaviour is important to notice when weimplement our own event providers.

5.23.2. Calendar Events

All occurrences in a calendar are represented as events. You have three ways to manage thecalendar events:

• Add events directly to the Calendar object using the addEvent()

• Use a Container as a data source

• Use the event provider mechanism

You can add events with addEvent() and remove them with the removeEvent(). Thesemethods will use the underlying event provider to write the modifications to the data source.

197Date Range and View Mode

User Interface Components

Page 200: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 5.62. Monthly view with All-Day and Normal Events

Figura 5.63. Weekly View

Event Interfaces and Providers

Events are handled though the CalendarEvent interface. The concrete class of the eventdepends on the specific CalendarEventProvider used in the calendar.

By default, Calendar uses a BasicEventProvider to provide events, which uses BasicEventinstances.

Calendar Events198

User Interface Components

Page 201: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Calendar does not depend on any particular data source implementation. Events are queried bythe Calendar from the provider that just has to implement the CalendarEventProviderinterface. It is up to the event provider that Calendar gets the correct events.

You can bind any Vaadin Container to a calendar, in which case a ContainerEventProvider isused transparently. The container must be ordered by start date and time of the events. SeeSecção 9.5, “Collecting Items in Containers” for basic information about containers.

Event Types

A calendar event requires a start time and an end time.These are the only mandatory properties.In addition, an event can also be set as an all-day event by setting the all-day property of theevent.You can also set the description of an event, which is displayed as a tooltip in the userinterface.

If the all-day field of the event is true, then the event is always rendered as an all-day event.In the monthly view, this means that no start time is displayed in the user interface and the eventhas an colored background. In the weekly view, all-day events are displayed in the upper part ofthe screen, and rendered similarly to the monthly view. In addition, when the time range of anevent is 24 hours or longer, it is rendered as an all-day event in the monthly view.

When the time range of an event is equal or less than 24 hours, with the accuracy of onemillisecond, the event is considered as a normal day event. Normal event has a start and endtimes that may be on different days.

Basic Events

The easiest way to add and manage events in a calendar is to use the basic event managementAPI. Calendar uses by default a BasicEventProvider, which keeps the events in memory in aninternal reprensetation.

For example, the following adds a two-hour event starting from the current time. The standardJava GregorianCalendar provides various ways to manipulate date and time.

// Add a two-hour eventGregorianCalendar start = new GregorianCalendar();GregorianCalendar end = new GregorianCalendar();end.add(java.util.Calendar.HOUR, 2);calendar.addEvent(new BasicEvent("Calendar study", "Learning how to use Vaadin Calendar", start.getTime(), end.getTime()));

This adds a new event that lasts for 3 hours. As the BasicEventProvider and BasicEvent implementsome optional event interfaces provided by the calendar package, there is no need to refreshthe calendar. Just create events, set their properties and add them to the Event Provider.

5.23.3. Getting Events from a Container

You can use any Vaadin Container that implements the Indexed interface as the data sourcefor calendar events.The Calendar will listen to change events from the container as well as writechanges to the container. You can attach a container to a Calendar withsetContainerDataSource().

In the following example, we bind a BeanItemContainer that contains built-in BasicEvent eventsto a calendar.

199Getting Events from a Container

User Interface Components

Page 202: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Create the calendarCalendar calendar = new Calendar("Bound Calendar");

// Use a container of built-in BasicEventsfinal BeanItemContainer<BasicEvent> container = new BeanItemContainer<BasicEvent>(BasicEvent.class);

// Create a meeting in the containercontainer.addBean(new BasicEvent("The Event", "Single Event", new GregorianCalendar(2012,1,14,12,00).getTime(), new GregorianCalendar(2012,1,14,14,00).getTime()));

// The container must be ordered by the start time. You// have to sort the BIC every time after you have added// or modified events.container.sort(new Object[]{"start"}, new boolean[]{true});

calendar.setContainerDataSource(container, "caption", "description", "start", "end", "styleName");

The container must either use the default property IDs for event data, as defined in theCalendarEvent interface, or provide them as parameters for the setContainerDataSource()method, as we did in the example above.

Keeping the Container Ordered

The events in the container must be kept ordered by their start date/time. Failing to do so mayand will result in the events not showing in the calendar properly.

Ordering depends on the container. With some containers, such as BeanItemContainer, youhave to sort the container explicitly every time after you have added or modified events, usuallywith the sort() method, as we did in the example above. Some container, such asJPAContainer, keep the in container automatically order if you provide a sorting rule.

For example, you could order a JPAContainer by the following rule, assuming that the startdate/time is held in the startDate property:

// The container must be ordered by start date. For JPAContainer// we can just set up sorting once and it will stay ordered.container.sort(new String[]{"startDate"}, new boolean[]{true});

Delegation of Event Management

Setting a container as the calendar data source with setContainerDataSource() automaticallyswitches to ContainerEventProvider. You can manipulate the event data through the API inCalendar and the user can move and resize event through the user interface.The event providerdelegates all such calendar operations to the container.

If you add events through the Calendar API, notice that you may be unable to create events ofthe type held in the container or adding them requires some container-specific operations. Insuch case, you may need to customize the addEvent() method.

For example, JPAContainer requires adding new items with addEntity().You could first addthe entity to the container or entity manager directly and then pass it to the addEvent(). Thatdoes not, however, work if the entity class does not implement CalendarEvent. This is actuallythe case always if the property names differ from the ones defined in the interface. You couldhandle creating the underlying entity objects in the addEvent() as follows:

Getting Events from a Container200

User Interface Components

Page 203: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Create a JPAContainerfinal JPAContainer<MyCalendarEvent> container = JPAContainerFactory.make(MyCalendarEvent.class, "book-examples");

// Customize the event provider for adding events// as entitiesContainerEventProvider cep = new ContainerEventProvider(container) { @Override public void addEvent(CalendarEvent event) { MyCalendarEvent entity = new MyCalendarEvent( event.getCaption(), event.getDescription(), event.getStart(), event.getEnd(), event.getStyleName()); container.addEntity(entity); }}

// Set the container as the data sourcecalendar.setEventProvider(cep);

// Now we can add events to the database through the calendarBasicEvent event = new BasicEvent("The Event", "Single Event", new GregorianCalendar(2012,1,15,12,00).getTime(), new GregorianCalendar(2012,1,15,14,00).getTime());calendar.addEvent(event);

5.23.4. Implementing an Event Provider

If the two simple ways of storing and managing events for a calendar are not enough, you mayneed to implement a custom event provider. It is the most flexible way of providing events. Youneed to attach the event provider to the Calendar using the setEventProvider() method.

Event queries are done by asking the event provider for all the events between two given dates.The range of these dates is guaranteed to be at least as long as the start and end dates set forthe component.The component can, however, ask for a longer range to ensure correct rendering.In particular, all start dates are expanded to the start of the day, and all end dates are expandedto the end of the day.

Custom Events

An event provider could use the built-in BasicEvent, but it is usually more proper to define acustom event type that is bound directly to the data source. Custom events may be useful forsome other purposes as well, such as when you need to add extra information to an event orcustomize how it is acquired.

Custom events must implement the CalendarEvent interface or extend an existing event class.The built-in BasicEvent class should serve as a good example of implementing simple events.It keeps the data in member variables.

public class BasicEvent implements CalendarEventEditor, EventChangeNotifier { ...

public String getCaption() { return caption; }

201Implementing an Event Provider

User Interface Components

Page 204: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

public String getDescription() { return description; }

public Date getEnd() { return end; }

public Date getStart() { return start; }

public String getStyleName() { return styleName; }

public boolean isAllDay() { return isAllDay; }

public void setCaption(String caption) { this.caption = caption; fireEventChange(); }

public void setDescription(String description) { this.description = description; fireEventChange(); }

public void setEnd(Date end) { this.end = end; fireEventChange(); }

public void setStart(Date start) { this.start = start; fireEventChange(); }

public void setStyleName(String styleName) { this.styleName = styleName; fireEventChange(); }

public void setAllDay(boolean isAllDay) { this.isAllDay = isAllDay; fireEventChange(); }

public void addEventChangeListener( EventChangeListener listener) { ... }

public void removeListener(EventChangeListener listener) { ... }

Implementing an Event Provider202

User Interface Components

Page 205: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

protected void fireEventChange() {...}}

You may have noticed that there was some additional code in the BasicEvent that was not inthe CalendarEvent interface. Namely BasicEvent also implements two additional interfaces:

CalendarEditorThis interface defines setters for all the fields, and is required for some of the defaulthandlers to work.

EventChangeNotifierThis interface adds the possibility to listen for changes in the event, and enables theCalendar to render the changes immediately.

The start time and end time are mandatory, but caption, description, and style name are not.Thestyle name is used as a part of the CSS class name for the HTML DOM element of the event.

In addition to the basic event interfaces, you can enhance the functionality of your event andevent provider classes by using the EventChange and EventSetChange events. They let theCalendar component to know about changes in events and update itself accordingly. TheBasicEvent and BasicEventProvider examples given earlier include a simple implementationof these interfaces.

Implementing the Event Provider

An event provider needs to implement the CalendarEventProvider interface. It has only onemethod to be implemented. Whenever the calendar is painted, getEvents(Date, Date)method is called and it must return a list of events between the given start and end time.

The following example implementation returns only one example event. The event starts fromthe current time and is five hours long.

public class MyEventProvider implements CalendarEventProvider{ public List<Event> getEvents(Date startDate, Date endDate){ List<Event> events = new ArrayList<Event>(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date());

Date start = cal.getTime(); cal.add(GregorianCalendar.HOUR, 5); Date end = cal.getTime(); BasicEvent event = new BasicEvent(); event.setCaption("My Event"); event.setDescription("My Event Description"); event.setStart(start); event.setEnd(end); events.add(event);

return events; }}

It is important to notice that the Calendar may query for dates beyond the range defined by startdate and end date. Particularly, it may expand the date range to make sure the user interface isrendered correctly.

203Implementing an Event Provider

User Interface Components

Page 206: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.23.5. Styling a Calendar

Configuring the appearance of the Vaadin Calendar component is one of the basic tasks. At theleast, you need to consider its sizing in your user interface. You also quite probably want to usesome color or colors for events.

Sizing

The Calendar supports component sizing as usual for defined (fixed or relative) sizes. Whenusing an undefined size for the calendar, all the sizes come from CSS. In addition, when theheight is undefined, a scrollbar is displayed in the weekly view to better fit the cells to the userinterface.

Below is a list of style rules that define the size of a Calendar with undefined size (these are thedefaults):

.v-calendar-month-sizedheight .v-calendar-month-day { height: 100px;}

.v-calendar-month-sizedwidth .v-calendar-month-day { width: 100px;}

.v-calendar-header-month-Hsized .v-calendar-header-day { width: 101px;}

/* for IE */.v-ie6 .v-calendar-header-month-Hsized .v-calendar-header-day { width: 104px;}

/* for others */.v-calendar-header-month-Hsized td:first-child { padding-left: 21px;}

.v-calendar-header-day-Hsized { width: 200px;}

.v-calendar-week-numbers-Vsized .v-calendar-week-number { height: 100px; line-height: 100px;}

.v-calendar-week-wrapper-Vsized { height: 400px; overflow-x: hidden !important;}

.v-calendar-times-Vsized .v-calendar-time { height: 38px;}

.v-calendar-times-Hsized .v-calendar-time { width: 42px;

Styling a Calendar204

User Interface Components

Page 207: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

}

.v-calendar-day-times-Vsized .v-slot,.v-calendar-day-times-Vsized .v-slot-even { height: 18px;}

.v-calendar-day-times-Hsized, .v-calendar-day-times-Hsized .v-slot,.v-calendar-day-times-Hsized .v-slot-even { width: 200px;}

Event Style

Events can be styled with CSS by setting them a style name suffix. The suffix is retrieved withthe getStyleName() method in CalendarEvent. If you use BasicEvent events, you can setthe suffix with setStyleName().

BasicEvent event = new BasicEvent("Wednesday Wonder", ... );event.setStyleName("mycolor");calendar.addEvent(event);

Suffix mycolor would create v-calendar-event-mycolor class for regular events andv-calendar-event-mycolor-add-day for all-day events. You could style the events withthe following rules:

.v-calendar .v-calendar-event-mycolor {}

.v-calendar .v-calendar-event-mycolor-all-day {}

.v-calendar .v-calendar-event-mycolor .v-calendar-event-caption {}

.v-calendar .v-calendar-event-mycolor .v-calendar-event-content {}

5.23.6. Visible Hours and Days

As we saw in Secção 5.23.1, “Date Range and View Mode”, you can set the range of dates thatare shown by the Calendar. But what if you wanted to show the entire month but hide theweekends? Or show only hours from 8 to 16 in the weekly view? The setVisibleDays() andsetVisibleHours() methods allow you to do that.

calendar.setVisibleDays(1,5); // Monday to Fridaycalendar.setVisibleHours(0,15); // Midnight until 4 pm

After the above settings, only weekdays from Monday to Friday would be shown. And when thecalendar is in the weekly view, only the time range from 00:00 to 16:00 would be shown.

Note that the excluded times are never shown so you should take care when setting the daterange. If the date range contains only dates / times that are excluded, nothing will be displayed.Also note that even if a date is not rendered because these settings, the event provider may stillbe queried for events for that date.

5.23.7. Drag and Drop

Vaadin Calendar can act as a drop target for drag and drop, described in Secção 11.12, “Dragand Drop”. With the functionality, the user could drag events, for example, from a table to acalendar.

205Visible Hours and Days

User Interface Components

Page 208: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

To support dropping, a Calendar must have a drop handler. When the drop handler is set, thedays in the monthly view and the time slots in the weekly view can receive drops. Other locations,such as day names in the weekly view, can not currently receive drops.

Calendar uses its own implementation of TargetDetails: CalendarTargetdetails. It holdsinformation about the the drop location, which in the context of Calendar means the date andtime. The drop target location can be retrieved via the getDropTime() method. If the drop isdone in the monthly view, the returned date does not have exact time information. If the drophappened in the weekly view, the returned date also contains the start time of the slot.

Below is a short example of creating a drop handler and using the drop information to create anew event:

private Calendar createDDCalendar() { Calendar calendar = new Calendar(); calendar.setDropHandler(new DropHandler() { public void drop(DragAndDropEvent event) { CalendarTargetDetails details = (CalendarTargetDetails) event.getTargetDetails();

TableTransferable transferable = (TableTransferable) event.getTransferable();

createEvent(details, transferable); removeTableRow(transferable); }

public AcceptCriterion getAcceptCriterion() { return AcceptAll.get(); }

});

return calendar;}

protected void createEvent(CalendarTargetDetails details, TableTransferable transferable) { Date dropTime = details.getDropTime(); java.util.Calendar timeCalendar = details.getTargetCalendar() .getInternalCalendar(); timeCalendar.setTime(dropTime); timeCalendar.add(java.util.Calendar.MINUTE, 120); Date endTime = timeCalendar.getTime();

Item draggedItem = transferable.getSourceComponent(). getItem(transferable.getItemId());

String eventType = (String)draggedItem. getItemProperty("type").getValue();

String eventDescription = "Attending: " + getParticipantString( (String[]) draggedItem. getItemProperty("participants").getValue());

BasicEvent newEvent = new BasicEvent(); newEvent.setAllDay(!details.hasDropTime());

Drag and Drop206

User Interface Components

Page 209: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

newEvent.setCaption(eventType); newEvent.setDescription(eventDescription); newEvent.setStart(dropTime); newEvent.setEnd(endTime);

BasicEventProvider ep = (BasicEventProvider) details .getTargetCalendar().getEventProvider(); ep.addEvent(newEvent);}

5.23.8. Using the Context Menu

Vaadin Calendar allows the use of context menu (mouse right-click) to manage events. As inother context menus in Vaadin, the menu items are handled in Vaadin as actions by an actionhandler. To enable a context menu, you have to implement a Vaadin Action.Handler andadd it to the calendar with addActionHandler().

An action handler must implement two methods: getActions() and handleAction(). ThegetActions() is called for each day displayed in the calendar view. It should return a list ofallowed actions for that day, that is, the items of the context menu. The target parameter is thecontext of the click - a CalendarDateRange that spans over the day.The sender is the Calendarobject.

The handleActions() receives the target context in the target. If the context menu wasopened on an event, the target is the Event object, otherwise it is a CalendarDateRange.

5.23.9. Localization and Formatting

Setting the Locale and Time Zone

Month and weekday names are shown in the language of the locale setting of the Calendar.Thetranslations are acquired from the standard Java locale data. By default, Calendar uses thesystem default locale for its internal calendar, but you can change it with setLocale(Localelocale). Setting the locale will update also other location specific date and time settings, suchas the first day of the week, time zone, and time format. However, time zone and time format canbe overridden by settings in the Calendar.

For example, the following would set the language to US English:

cal.setLocale(Locale.US);

The locale defines the default time zone. You can change it with the setTimeZone() method,which takes a java.util.TimeZone object as its parameter. Setting timezone to null will resettimezone to the locale default.

For example, the following would set the Finnish time zone, which is EET

cal.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));

Time and Date Caption Format

The time may be shown either in 24 or 12 hour format.The default format is defined by the locale,but you can change it with the setTimeFormat() method. Giving a null setting will reset thetime format to the locale default.

cal.setTimeFormat(TimeFormat.Format12H);

207Using the Context Menu

User Interface Components

Page 210: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

You can change the format of the date captions in the week view with thesetWeeklyCaptionFormat(String dateFormatPattern) method.The date format patternshould follow the format of the standard Java java.text.SimpleDateFormat class.

For example:

cal.setWeeklyCaptionFormat("dd-MM-yyyy");

5.23.10. Customizing the Calendar

In this section, we give a tutorial for how to make various basic customizations of the VaadinCalendar. The event provider and styling was described earlier, so now we concentrate on otherfeatures of the Calendar API.

Overview of Handlers

Most of the handlers related to calendar events have sensible default handlers. These are foundin the com.vaadin.ui.handler package.The default handlers and their functionalities are describedbelow.

• BasicBackwardHandler. Handles clicking the back-button of the weekly view so thatthe viewed month is changed to the previous one.

• BasicForwardHandler. Handles clicking the forward-button of the weekly view so thatthe viewed month is changed to the next one.

• BasicWeekClickHandler. Handles clicking the week numbers int the monthly view sothat the viewable date range is changed to the clicked week.

• BasicDateClickHandler. Handles clicking the dates on both the monthly view and theweekly view. Changes the viewable date range so that only the clicked day is visible.

• BasicEventMoveHandler. Handles moving the events in both monthly view and theweekly view. Events can be moved and their start and end dates are changed correctly,but only if the event implements CalendarEventEditor (implemented by BasicEvent).

• BasicEventResizeHandler. Handles resizing the events in the weekly view. Events canbe resized and their start and end dates are changed correctly, but only if the eventimplements CalendarEventEditor (implemented by the BasicEvent).

All of these handlers are automatically set when creating a new Calendar. If you wish to disablesome of the default functionality, you can simply set the corresponding handler to null. This willprevent the functionality from ever appearing on the user interface. For example, if you set theEventMoveHandler to null, the user will be unable to move events in the browser.

Creating a Calendar

Let us first create a new Calendar instance. Here we use our own event provider, theMyEventProvider described in “Implementing the Event Provider”.

Calendar cal = new Calendar(new MyEventProvider());

This initializes the Calendar. To customize the viewable date range, we must set a start and enddate to it.

Customizing the Calendar208

User Interface Components

Page 211: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

There is only one visible event in the timeline, starting from the current time. That is what ourevent provider passes to the client.

It would be nice to also be able to control the navigation forward and backward. The defaultnavigation is provided by the default handlers, but perhaps we want to restrict the users so theycan only navigate dates in the current year. Maybe we also want to pose some other restrictionsto the clicking week numbers and dates.

These restrictions and other custom logic can be defined with custom handlers.You can find thehandlers in the com.vaadin.addon.calendar.ui.handler package and they can be easily extended.Note that if you don not want to extend the default handlers, you are free to implement your own.The interfaces are described in CalendarComponentEvents.

5.23.11. Backward and Forward Navigation

Vaadin Calendar has only limited built-in navigation support. The weekly view has navigationbuttons in the top left and top right corners.

You can handle backward and forward navigation with a BackwardListener andForwardListener.

cal.setHandler(new BasicBackwardHandler() { protected void setDates(BackwardEvent event, Date start, Date end) {

java.util.Calendar calendar = event.getComponent() .getInternalCalendar(); if (isThisYear(calendar, end) && isThisYear(calendar, start)) { super.setDates(event, start, end); } }});

The forward navigation handler can be implemented in the same way. The example handlerrestricts the dates to the current year.

5.23.12. Date Click Handling

By default, clicking a date either in month or week view switches to single-day view. The dateclick event is handled by a DateClickHandler.

The following example handles click events so that when the user clicks the date header in theweekly view, it will switch to single-day view, and in the single-day view switch back to the weeklyview.

cal.setHandler(new BasicDateClickHandler() { public void dateClick(DateClickEvent event) { Calendar cal = event.getComponent(); long currentCalDateRange = cal.getEndDate().getTime() - cal.getStartDate().getTime();

if (currentCalDateRange < VCalendar.DAYINMILLIS) { // Change the date range to the current week cal.setStartDate(cal.getFirstDateForWeek(event.getDate())); cal.setEndDate(cal.getLastDateForWeek(event.getDate()));

} else {

209Backward and Forward Navigation

User Interface Components

Page 212: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Default behaviour, change date range to one day super.dateClick(event); } }});

5.23.13. Handling Week Clicks

The monthly view displays week numbers for each week row on the left side of the date grid.Theweek number are clickable and you can handle the click events by setting a WeekClickHandlerfor the Calendar object. The default handler changes the date range to be the clicked week.

In the following example, we add a week click handler that changes the date range of the calendarto one week only if the start and end dates of the week are in the current month.

cal.setHandler(new BasicWeekClickHandler() { protected void setDates(WeekClick event, Date start, Date end) { java.util.Calendar calendar = event.getComponent() .getInternalCalendar(); if (isThisMonth(calendar, start) && isThisMonth(calendar, end)) { super.setDates(event, start, end); } }});

5.23.14. Handling Event Clicks

The calendar events in all views are are clickable. There is no default handler. Just like the dateand week click handlers, event click handling is enabled by setting an EventClickHandlerfor the Calendar object.

You can get hold of the clicked event by the getCalendarEvent() method in the EventClickobject passed to the handler, as shown in the following example.

cal.setHandler(new EventClickHandler() { public void eventClick(EventClick event) { BasicEvent e = (BasicEvent) event.getCalendarEvent();

// Do something with it new Notification("Event clicked: " + e.getCaption(), e.getDescription()).show(Page.getCurrent()); }});

5.23.15. Event Dragging

The user can drag an event to change its position in time. The default handler sets the start andend time of the event accordingly. You can do many things with a custom move handler, suchas restrict moving events.

In the following example, we add a EventMoveHandler to a Calendar. The event handlerupdates the new position to the datasource, but only if the new dates are in the current month.This requires making some changes to the event provider class.

Handling Week Clicks210

User Interface Components

Page 213: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

cal.setHandler(new BasicEventMoveHandler() { private java.util.Calendar javaCalendar;

public void eventMove(MoveEvent event) { javaCalendar = event.getComponent().getInternalCalendar(); super.eventMove(event); }

protected void setDates(CalendarEventEditor event, Date start, Date end) { if (isThisMonth(javaCalendar, start) && isThisMonth(javaCalendar, end)) { super.setDates(event, start, end); } }});

For the above example to work, the example event provider presented earlier needs to be changedslightly so that it doesn't always create a new event when getEvents() is called.

public static class MyEventProvider implements CalendarEventProvider { private List<CalendarEvent> events = new ArrayList<CalendarEvent>();

public MyEventProvider() { events = new ArrayList<CalendarEvent>(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date());

Date start = cal.getTime(); cal.add(GregorianCalendar.HOUR, 5); Date end = cal.getTime(); BasicEvent event = new BasicEvent(); event.setCaption("My Event"); event.setDescription("My Event Description"); event.setStart(start); event.setEnd(end); events.add(event); }

public void addEvent(CalendarEvent BasicEvent) { events.add(BasicEvent); }

public List<CalendarEvent> getEvents(Date startDate, Date endDate) { return events; }}

After these changes, the user can move events around as earlier, but dropping an event, thestart and end dates are checked by the server. Note that as the server-side must move the eventin order for it to render to the place it was dropped.The server can also reject moves by not doinganything when the event is received.

211Event Dragging

User Interface Components

Page 214: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.23.16. Handling Drag Selection

Drag selection works both in the monthly and weekly views. To listen for drag selection, you canadd a RangeSelectListener to the Calendar. There is no default handler for range select.

In the code example below, we create an new event when any date range is selected. Dragselection opens a window where the user is asked for a caption for the new event. After confirming,the new event is be passed to the event provider and calendar is updated. Note that as ourexample event provider and event classes do not implement the event change interface, we mustrefresh the Calendar manually after changing the events.

cal.setHandler(new RangeSelectHandler() { public void rangeSelect(RangeSelectEvent event) { BasicEvent calendarEvent = new BasicEvent(); calendarEvent.setStart(event.getStart()); calendarEvent.setEnd(event.getEnd());

// Create popup window and add a form in it. VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); layout.setSpacing(true);

final Window w = new Window(null, layout); ...

// Wrap the calendar event to a BeanItem // and pass it to the form final BeanItem<CalendarEvent> item = new BeanItem<CalendarEvent>(myEvent);

final Form form = new Form(); form.setItemDataSource(item); ...

layout.addComponent(form);

HorizontalLayout buttons = new HorizontalLayout(); buttons.setSpacing(true); buttons.addComponent(new Button("OK", new ClickListener() {

public void buttonClick(ClickEvent event) { form.commit();

// Update event provider's data source provider.addEvent(item.getBean());

UI.getCurrent().removeWindow(w); } }));

... }});

Handling Drag Selection212

User Interface Components

Page 215: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

5.23.17. Resizing Events

The user can resize an event by dragging from both ends to change its start or end time. Thisoffers a convenient way to change event times without the need to type anything. The defaultresize handler sets the start and end time of the event according to the resize.

In the example below, we set a custom handler for resize events.The handler prevents any eventto be resized over 12 hours in length. Note that this does not prevent the user from resizing anevent over 12 hours in the client. The resize will just be corrected by the server.

cal.setHandler(new BasicEventResizeHandler() { private static final long twelveHoursInMs = 12*60*60*1000;

protected void setDates(CalendarEventEditor event, Date start, Date end) { long eventLength = end.getTime() - start.getTime(); if (eventLength <= twelveHoursInMs) { super.setDates(event, start, end); } }});

5.24. Component Composition with CustomComponent

The ease of making new user interface components is one of the core features of Vaadin.Typically,you simply combine existing built-in components to produce composite components. In manyapplications, such composite components make up the majority of the user interface.

To create a composite component, you need to inherit the CustomComponent and call thesetCompositionRoot() in the constructor to set the composition root component. The rootcomponent is typically a layout component that contains multiple components.

For example:

class MyComposite extends CustomComponent { public MyComposite(String message) { // A layout structure used for composition Panel panel = new Panel("My Custom Component"); panel.setContent(new VerticalLayout());

// Compose from multiple components Label label = new Label(message); label.setSizeUndefined(); // Shrink panel.addComponent(label); panel.addComponent(new Button("Ok"));

// Set the size as undefined at all levels panel.getContent().setSizeUndefined(); panel.setSizeUndefined(); setSizeUndefined();

// The composition root MUST be set setCompositionRoot(panel); }}

213Resizing Events

User Interface Components

Page 216: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Take note of the sizing when trying to make a customcomponent that shrinks to fit the containedcomponents. You have to set the size as undefined at all levels; the sizing of the compositecomponent and the composition root are separate.

You can use the component as follows:

MyComposite mycomposite = new MyComposite("Hello");

The rendered component is shown in Figura 5.64, “A Custom Composite Component”.

Figura 5.64. A Custom Composite Component

You can also inherit any other components, such as layouts, to attain similar composition. Evenfurther, you can create entirely new low-level components, by integrating pure client-sidecomponents or by extending the client-side functionality of built-in components. Development ofnew components is covered in Capítulo 16, Integrating with the Server-Side.

5.25. Composite Fields with CustomField

The CustomField is a way to create composite components like with CustomComponent,except that it implements the Field interface and inherit AbstractField, described in Secção 5.4,“Field Components”. A field allows editing a property value in the Vaadin data model, and canbe bound to data with field groups, as described in Secção 9.4, “Creating Forms by Binding Fieldsto Items”. The field values are buffered and can be validated with validators.

A composite field class must implement the getType() and initContent() methods. Thelatter should return the content composite of the field. It is typically a layout component, but canbe any component.

It is also possible to override validate(), setInternalValue(), commit(),setPropertyDataSource, isEmpty() and other methods to implement different functionalitiesin the field. Methods overriding setInternalValue() should call the superclass method.

Composite Fields with CustomField214

User Interface Components

Page 217: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 6

Managing Layout

6.1. Overview ................................................................................................ 2166.2. UI, Window, and Panel Content ............................................................. 2186.3. VerticalLayout and HorizontalLayout ................................................. 2186.4. GridLayout ............................................................................................ 2236.5. FormLayout .......................................................................................... 2276.6. Panel ..................................................................................................... 2296.7. Sub-Windows ........................................................................................ 2316.8. HorizontalSplitPanel and VerticalSplitPanel ...................................... 2346.9. TabSheet ............................................................................................... 2366.10. Accordion ........................................................................................... 2406.11. AbsoluteLayout .................................................................................. 2416.12. CssLayout .......................................................................................... 2446.13. Layout Formatting ................................................................................ 2466.14. Custom Layouts ................................................................................... 251

Ever since the ancient xeroxians invented graphical user interfaces, programmers have wantedto make GUI programming ever easier for themselves. Solutions started simple. When GUIsappeared on PC desktops, practically all screens were of the VGA type and fixed into 640x480size. Mac or X Window System on UNIX were not much different. Everyone was so happy withsuch awesome graphics resolutions that they never thought that an application would have towork on a radically different screen size. At worst, screens could only grow, they thought, givingmore space for more windows. In the 80s, the idea of having a computer screen in your pocketwas simply not realistic. Hence, the GUI APIs allowed placing UI components using screencoordinates.Visual Basic and some other systems provided an easy way for the designer to dragand drop components on a fixed-sized window. One would have thought that at least translatorswould have complained about the awkwardness of such a solution, but apparently they were not,

215Book of Vaadin

Page 218: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

as non-engineers, heard or at least cared about. At best, engineers could throw at them a resourceeditor that would allow them to resize the UI components by hand. Such was the spirit back then.

After the web was born, layout design was doomed to change for ever. At first, layout didn't mattermuch, as everyone was happy with plain headings, paragraphs, and a few hyperlinks here andthere. Designers of HTML wanted the pages to run on any screen size. The screen size wasactually not pixels but rows and columns of characters, as the baby web was really just hypertext,not graphics.That was soon to be changed.The first GUI-based browser, NCSA Mosaic, launcheda revolution that culminated in Netscape Navigator. Suddenly, people who had previously beendoing advertisement brochures started writing HTML. This meant that layout design had to beeasy not just for programmers, but also allow the graphics designer to do his or her job withouthaving to know a thing about programming.The W3C committee designing web standards cameup with the CSS (Cascading Style Sheet) specification, which allowed trivial separation ofappearance from content. Later versions of HTML followed, XHTML appeared, as did countlessother standards.

Page description and markup languages are a wonderful solution for static presentations, suchas books and most web pages. Real applications, however, need to have more control. Theyneed to be able to change the state of user interface components and even their layout on therun. This creates a need to separate the presentation from content on exactly the right level.

Thanks to the attack of graphics designers, desktop applications were, when it comes toappearance, far behind web design. Sun Microsystems had come in 1995 with a new programminglanguage, Java, for writing cross-platform desktop applications. Java's original graphical userinterface toolkit, AWT (Abstract Windowing Toolkit), was designed to work on multiple operatingsystems as well as embedded in web browsers. One of the special aspects of AWT was thelayout manager, which allowed user interface components to be flexible, growing and shrinkingas needed. This made it possible for the user to resize the windows of an application flexibly andalso served the needs of localization, as text strings were not limited to some fixed size in pixels.It became even possible to resize the pixel size of fonts, and the rest of the layout adapted to thenew size.

Layout management of Vaadin is a direct successor of the web-based concept for separation ofcontent and appearance and of the Java AWT solution for binding the layout and user interfacecomponents into objects in programs. Vaadin layout components allow you to position your UIcomponents on the screen in a hierarchical fashion, much like in conventional Java UI toolkitssuch as AWT, Swing, or SWT. In addition, you can approach the layout from the direction of theweb with the CustomLayout component, which you can use to write your layout as a templatein XHTML that provides locations of any contained components. The AbsoluteLayout allowsthe old-style pixel-position based layouting, but it also supports percentual values, which makesit usable for scalable layouts. It is also useful as an area on which the user can position itemswith drag and drop.

The moral of the story is that, because Vaadin is intended for web applications, appearance isof high importance. The solutions have to be the best of both worlds and satisfy artists of bothkind: code and graphics. On the API side, the layout is controlled by UI components, particularlythe layout components. On the visual side, it is controlled by themes. Themes can contain anyHTML, Sass, CSS, and JavaScript that you or your web artists create to make people feel goodabout your software.

6.1. Overview

The user interface components in Vaadin can roughly be divided in two groups: components thatthe user can interact with and layout components for placing the other components to specific

Overview216

Managing Layout

Page 219: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

places in the user interface. The layout components are identical in their purpose to layoutmanagers in regular desktop frameworks for Java and you can use plain Java to accomplishsophisticated component layouting.

You start by creating a content layout for the UI and then add other layout componentshierarchically, and finally the interaction components as the leaves of the component tree.

// Set the root layout for the UIVerticalLayout content = new VerticalLayout();setContent(content);

// Add the topmost component.content.addComponent(new Label("The Ultimate Cat Finder"));

// Add a horizontal layout for the bottom part.HorizontalLayout bottom = new HorizontalLayout();content.addComponent(bottom);

bottom.addComponent(new Tree("Major Planets and Their Moons"));bottom.addComponent(new Panel());...

You will usually need to tune the layout components a bit by setting sizes, expansion ratios,alignments, spacings, and so on. The general settings are described in Secção 6.13, “LayoutFormatting”.

Layouts are coupled with themes that specify various layout features, such as backgrounds,borders, text alignment, and so on. Definition and use of themes is described in Capítulo 8,Themes

You can see a finished version of the above example in Figura 6.1, “Layout Example”.

Figura 6.1. Layout Example

The alternative for using layout components is to use the special CustomLayout that allowsusing HTML templates. This way, you can let the web page designers take responsibility ofcomponent layouting using their own set of tools. What you lose is the ability to manage thelayout dynamically.

217Overview

Managing Layout

Page 220: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The Visual Editor

While you can always program the layout by hand, the Vaadin plugin for the EclipseIDE includes a visual (WYSIWYG) editor that you can use to create user interfacesvisually. The editor generates the code that creates the user interface and is usefulfor rapid application development and prototyping. It is especially helpful when youare still learning the framework, as the generated code, which is designed to be asreusable as possible, also works as an example of how you create user interfaceswith Vaadin. You can find more about the editor in Capítulo 7, Visual User InterfaceDesign with Eclipse.

6.2. UI, Window, and Panel Content

The UI, Window, and its superclass Panel all have a single content component, which you needto set with setContent().The content is usually a layout component, although any componentis allowed.

Panel panel = new Panel("This is a Panel");VerticalLayout panelContent = new VerticalLayout();panelContent.addComponent(new Label("Hello!"));panel.setContent(panelContent);

// Set the panel as the content of the UIsetContent(panel);

The size of the content is the default size of the particular layout component, for example, aVerticalLayout has 100% width and undefined height by default (this coincides with the defaultsfor Panel and Label). If such a layout with undefined height grows higher than the browserwindow, it will flow out of the view and scrollbars will appear. In many applications, you want touse the full area of the browser view. Setting the components contained inside the content layoutto full size is not enough, and would actually lead to an invalid state if the height of the contentlayout is undefined.

// First set the root content for the UIVerticalLayout content = new VerticalLayout();setContent(content);

// Set the content size to full width and heightcontent.setSizeFull();

// Add a title area on top of the screen. This takes// just the vertical space it needs.content.addComponent(new Label("My Application"));

// Add a menu-view area that takes rest of vertical spaceHorizontalLayout menuview = new HorizontalLayout();menuview.setSizeFull();content.addComponent(menuview);

See Secção 6.13.1, “Layout Size” for more information about setting layout sizes.

6.3. VerticalLayout and HorizontalLayout

VerticalLayout and HorizontalLayout are ordered layouts for laying components out eithervertically or horizontally, respectively. They both extend from AbstractOrderedLayout, together

UI, Window, and Panel Content218

Managing Layout

Page 221: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

with the FormLayout. These are the two most important layout components in Vaadin, andtypically you have a VerticalLayout as the root content component of the UI.

VerticalLayout has 100% default width and undefined height, so it fills the containing layout (orUI) horizontally, and fits its content vertically. HorizontalLayout has undefined size in bothdimensions.

Typical use of the layouts goes as follows:

VerticalLayout vertical = new VerticalLayout ();vertical.addComponent(new TextField("Name"));vertical.addComponent(new TextField("Street address"));vertical.addComponent(new TextField("Postal code"));layout.addComponent(vertical);

The component captions are placed above the component, so the layout will look as follows:

Using HorizontalLayout gives the following layout:

6.3.1. Spacing in Ordered Layouts

The ordered layouts can have spacing between the horizontal or vertical cells. The spacing canbe enabled with setSpacing(true).

The spacing as a default height or width, which can be customized in CSS. You need to set theheight or width for spacing elements with v-spacing style.You also need to specify an enclosingrule element in a CSS selector, such as v-verticallayout for a VerticalLayout orv-horizontallayout for a HorizontalLayout. You can also use v-vertical andv-horizontal for all vertically or horizontally ordered layouts, such as FormLayout.

For example, the following sets the amount of spacing for all VerticalLayouts, as well asFormLayout, in the UI:

.v-vertical > .v-spacing { height: 30px;}

Or for HorizontalLayout:

.v-horizontal > .v-spacing { width: 50px;}

219Spacing in Ordered Layouts

Managing Layout

Page 222: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.3.2. Sizing Contained Components

The components contained within an ordered layout can be laid out in a number of different waysdepending on how you specify their height or width in the primary direction of the layout component.

Figura 6.2. Component Widths in HorizontalLayout

Figura 6.2, “Component Widths in HorizontalLayout” above gives a summary of the sizingoptions for a HorizontalLayout. The figure is broken down in the following subsections.

Layout with Undefined Size

If a VerticalLayout has undefined height or HorizontalLayout undefined width, the layout willshrink to fit the contained components so that there is no extra space between them.

HorizontalLayout fittingLayout = new HorizontalLayout();fittingLayout.setWidth(Sizeable.SIZE_UNDEFINED, 0); // DefaultfittingLayout.addComponent(new Button("Small"));fittingLayout.addComponent(new Button("Medium-sized"));fittingLayout.addComponent(new Button("Quite a big component"));parentLayout.addComponent(fittingLayout);

The both layouts actually have undefined height by default and HorizontalLayout has alsoundefined width, while VerticalLayout has 100% relative width.

If such a vertical layout with undefined height continues below the bottom of a window (a Windowobject), the window will pop up a vertical scroll bar on the right side of the window area.This way,you get a "web page". The same applies to Panel.

A layout that contains components with percentual size must have a definedsize!

If a layout has undefined size and a contained component has, say, 100% size, thecomponent would fill the space given by the layout, while the layout would shrink tofit the space taken by the component, which would be a paradox. This requirementholds for height and width separately. The debug window allows detecting suchinvalid cases; see Secção 11.3.5, “Inspecting Component Hierarchy”.

An exception to the above rule is a case where you have a layout with undefined size that containsa component with a fixed or undefined size together with one or more components with relativesize. In this case, the contained component with fixed (or undefined) size in a sense defines the

Sizing Contained Components220

Managing Layout

Page 223: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

size of the containing layout, removing the paradox.That size is then used for the relatively sizedcomponents.

The technique can be used to define the width of a VerticalLayout or the height of aHorizontalLayout.

// Vertical layout would normally have 100% widthVerticalLayout vertical = new VerticalLayout();

// Shrink to fit the width of contained componentsvertical.setWidth(Sizeable.SIZE_UNDEFINED, 0);

// Label has normally 100% width, but we set it as// undefined so that it will take only the needed spaceLabel label = new Label("\u2190 The VerticalLayout shrinks to fit "+ "the width of this Label \u2192");label.setWidth(Sizeable.SIZE_UNDEFINED, 0);vertical.addComponent(label);

// Button has undefined width by defaultButton butt = new Button("\u2190 This Button takes 100% "+ "of the width \u2192");butt.setWidth("100%");vertical.addComponent(butt);

Figura 6.3. Defining the Size with a Component

Layout with Defined Size

If you set a HorizontalLayout to a defined size horizontally or a VerticalLayout vertically, andthere is space left over from the contained components, the extra space is distributed equallybetween the component cells. The components are aligned within these cells according to theiralignment setting, top left by default, as in the example below.

fixedLayout.setWidth("400px");

Using percentual sizes for components contained in a layout requires answering the question,"Percentage of what?" There is no sensible default answer for this question in the currentimplementation of the layouts, so in practice, you may not define "100%" size alone.

Expanding Components

Often, you want to have one component that takes all the available space left over from othercomponents.You need to set its size as 100% and set it as expanding with setExpandRatio().The second parameter for the method is an expansion ratio, which is relevant if there are morethan one expanding component, but its value is irrelevant for a single expanding component.

221Sizing Contained Components

Managing Layout

Page 224: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

HorizontalLayout layout = new HorizontalLayout();layout.setWidth("400px");

// These buttons take the minimum size.layout.addComponent(new Button("Small"));layout.addComponent(new Button("Medium-sized"));

// This button will expand.Button expandButton = new Button("Expanding component");

// Use 100% of the expansion cell's width.expandButton.setWidth("100%");

// The component must be added to layout before setting the ratio.layout.addComponent(expandButton);

// Set the component's cell to expand.layout.setExpandRatio(expandButton, 1.0f);

parentLayout.addComponent(layout);

Notice that you must call setExpandRatio() after addComponent(), because the layout cannot operate on an component that it doesn't (yet) include.

Expand Ratios

If you specify an expand ratio for multiple components, they will all try to use the available spaceaccording to the ratio.

HorizontalLayout layout = new HorizontalLayout();layout.setWidth("400px");

// Create three equally expanding components.String[] captions = { "Small", "Medium-sized", "Quite a big component" };for (int i = 1; i <= 3; i++) { Button button = new Button(captions[i-1]); button.setWidth("100%"); layout.addComponent(button);

// Have uniform 1:1:1 expand ratio. layout.setExpandRatio(button, 1.0f);}

As the example used the same ratio for all components, the ones with more content may havethe content cut. Below, we use differing ratios:

// Expand ratios for the components are 1:2:3.layout.setExpandRatio(button, i * 1.0f);

Sizing Contained Components222

Managing Layout

Page 225: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

If the size of the expanding components is defined as a percentage (typically "100%"), the ratiois calculated from the overall space available for the relatively sized components. For example,if you have a 100 pixels wide layout with two cells with 1.0 and 4.0 respective expansion ratios,and both the components in the layout are set as setWidth("100%"), the cells will haverespective widths of 20 and 80 pixels, regardless of the minimum size of the components.

However, if the size of the contained components is undefined or fixed, the expansion ratio is ofthe excess available space. In this case, it is the excess space that expands, not the components.

for (int i = 1; i <= 3; i++) { // Button with undefined size. Button button = new Button(captions[i - 1]);

layout4.addComponent(button);

// Expand ratios are 1:2:3. layout4.setExpandRatio(button, i * 1.0f);}

It is not meaningful to combine expanding components with percentually defined size andcomponents with fixed or undefined size. Such combination can lead to a very unexpected sizefor the percentually sized components.

Percentage of Cells

A percentual size of a component defines the size of the component within its cell. Usually, youuse "100%", but a smaller percentage or a fixed size (smaller than the cell size) will leave anempty space in the cell and align the component within the cell according to its alignment setting,top left by default.

HorizontalLayout layout50 = new HorizontalLayout();layout50.setWidth("400px");

String[] captions1 = { "Small 50%", "Medium 50%", "Quite a big 50%" };for (int i = 1; i <= 3; i++) { Button button = new Button(captions1[i-1]); button.setWidth("50%"); layout50.addComponent(button);

// Expand ratios for the components are 1:2:3. layout50.setExpandRatio(button, i * 1.0f);}parentLayout.addComponent(layout50);

6.4. GridLayout

GridLayout container lays components out on a grid, defined by the number of columns androws. The columns and rows of the grid serve as coordinates that are used for laying out

223GridLayout

Managing Layout

Page 226: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

components on the grid. Each component can use multiple cells from the grid, defined as anarea (x1,y1,x2,y2), although they typically take up only a single grid cell.

The grid layout maintains a cursor for adding components in left-to-right, top-to-bottom order. Ifthe cursor goes past the bottom-right corner, it will automatically extend the grid downwards byadding a new row.

The following example demonstrates the use of GridLayout. The addComponent takes acomponent and optional coordinates. The coordinates can be given for a single cell or for anarea in x,y (column,row) order. The coordinate values have a base value of 0. If coordinates arenot given, the cursor will be used.

// Create a 4 by 4 grid layout.GridLayout grid = new GridLayout(4, 4);grid.addStyleName("example-gridlayout");

// Fill out the first row using the cursor.grid.addComponent(new Button("R/C 1"));for (int i = 0; i < 3; i++) { grid.addComponent(new Button("Col " + (grid.getCursorX() + 1)));}

// Fill out the first column using coordinates.for (int i = 1; i < 4; i++) { grid.addComponent(new Button("Row " + i), 0, i);}

// Add some components of various shapes.grid.addComponent(new Button("3x1 button"), 1, 1, 3, 1);grid.addComponent(new Label("1x2 cell"), 1, 2, 1, 3);InlineDateField date = new InlineDateField("A 2x2 date field");date.setResolution(DateField.RESOLUTION_DAY);grid.addComponent(date, 2, 2, 3, 3);

The resulting layout will look as follows. The borders have been made visible to illustrate thelayout cells.

Figura 6.4.The Grid Layout Component

A component to be placed on the grid must not overlap with existing components. A conflictcauses throwing a GridLayout.OverlapsException.

GridLayout224

Managing Layout

Page 227: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.4.1. Sizing Grid Cells

You can define the size of both a grid layout and its components in either fixed or percentualunits, or leave the size undefined altogether, as described in Secção 5.3.9, “Sizing Components”.Secção 6.13.1, “Layout Size” gives an introduction to sizing of layouts.

The size of the GridLayout component is undefined by default, so it will shrink to fit the size ofthe components placed inside it. In most cases, especially if you set a defined size for the layoutbut do not set the contained components to full size, there will be some unused space. Theposition of the non-full components within the grid cells will be determined by their alignment.See Secção 6.13.3, “Layout Cell Alignment” for details on how to align the components insidethe cells.

The components contained within a GridLayout layout can be laid out in a number of differentways depending on how you specify their height or width. The layout options are similar toHorizontalLayout and VerticalLayout, as described in Secção 6.3, “VerticalLayout andHorizontalLayout”.

A layout that contains components with percentual size must have a definedsize!

If a layout has undefined size and a contained component has, say, 100% size, thecomponent would fill the space given by the layout, while the layout would shrink tofit the space taken by the component, which is a paradox. This requirement holdsfor height and width separately.The debug mode allows detecting such invalid cases;see Secção 11.3.1, “Enabling the Debug Mode”.

Often, you want to have one or more rows or columns that take all the available space left overfrom non-expanding rows or columns. You need to set the rows or columns as expanding withsetRowExpandRatio() and setColumnExpandRatio(). The first parameter for thesemethods is the index of the row or column to set as expanding. The second parameter for themethods is an expansion ratio, which is relevant if there are more than one expanding row orcolumn, but its value is irrelevant if there is only one. With multiple expanding rows or columns,the ratio parameter sets the relative portion how much a specific row/column will take in relationwith the other expanding rows/columns.

GridLayout grid = new GridLayout(3,2);

// Layout containing relatively sized components must have// a defined size, here is fixed size.grid.setWidth("600px");grid.setHeight("200px");

// Add some contentString labels [] = { "Shrinking column<br/>Shrinking row", "Expanding column (1:)<br/>Shrinking row", "Expanding column (5:)<br/>Shrinking row", "Shrinking column<br/>Expanding row", "Expanding column (1:)<br/>Expanding row", "Expanding column (5:)<br/>Expanding row"};for (int i=0; i<labels.length; i++) { Label label = new Label(labels[i], Label.CONTENT_XHTML); label.setWidth(null); // Set width as undefined grid.addComponent(label);

225Sizing Grid Cells

Managing Layout

Page 228: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

}

// Set different expansion ratios for the two columnsgrid.setColumnExpandRatio(1, 1);grid.setColumnExpandRatio(2, 5);

// Set the bottom row to expandgrid.setRowExpandRatio(1, 1);

// Align and size the labels.for (int col=0; col<grid.getColumns(); col++) { for (int row=0; row<grid.getRows(); row++) { Component c = grid.getComponent(col, row); grid.setComponentAlignment(c, Alignment.TOP_CENTER);

// Make the labels high to illustrate the empty // horizontal space. if (col != 0 || row != 0) c.setHeight("100%"); }}

Figura 6.5. Expanding Rows and Columns in GridLayout

If the size of the contained components is undefined or fixed, the expansion ratio is of the excessspace, as in Figura 6.5, “Expanding Rows and Columns in GridLayout” (excess horizontal spaceis shown in white). However, if the size of the all the contained components in the expandingrows or columns is defined as a percentage, the ratio is calculated from the overall space availablefor the percentually sized components. For example, if we had a 100 pixels wide grid layout withtwo columns with 1.0 and 4.0 respective expansion ratios, and all the components in the gridwere set as setWidth("100%"), the columns would have respective widths of 20 and 80 pixels,regardless of the minimum size of their contained components.

6.4.1. CSS Style Rules

.v-gridlayout {}

.v-gridlayout-margin {}

The v-gridlayout is the root element of the GridLayout component. The v-gridlayout-margin is asimple element inside it that allows setting a padding between the outer element and the cells.

For styling the individual grid cells, you should style the components inserted in the cells. Theimplementation structure of the grid can change, so depending on it, as is done in the examplebelow, is not generally recommended. Normally, if you want to have, for example, a differentcolor for a certain cell, just make set the component inside it setSizeFull(), and add a style

CSS Style Rules226

Managing Layout

Page 229: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

name for it. Sometimes you may need to use a layout component between a cell and its actualcomponent just for styling.

The following example shows how to make the grid borders visible, as in Figura 6.5, “ExpandingRows and Columns in GridLayout”.

.v-gridlayout-gridexpandratio { background: blue; /* Creates a "border" around the grid. */ margin: 10px; /* Empty space around the layout. */}

/* Add padding through which the background color shows. */.v-gridlayout-gridexpandratio .v-gridlayout-margin { padding: 2px; }

/* Add cell borders and make the cell backgrounds white. * Warning: This depends heavily on the HTML structure. */.v-gridlayout-gridexpandratio > div > div > div { padding: 2px; /* Layout background will show through. */ background: white; /* The cells will be colored white. */}

/* Components inside the layout are a safe way to style cells. */.v-gridlayout-gridexpandratio .v-label { text-align: left; background: #ffffc0; /* Pale yellow */}

You should beware of margin, padding, and border settings in CSS as they can mess up thelayout. The dimensions of layouts are calculated in the Client-Side Engine of Vaadin and somesettings can interfere with these calculations. For more information, on margins and spacing, seeSecção 6.13.4, “Layout Cell Spacing” and Secção 6.13.5, “Layout Margins”

6.5. FormLayout

FormLayout lays the components and their captions out in two columns, with optional indicatorsfor required fields and errors that can be shown for each field. The field captions can have anicon in addition to the text. FormLayout is an ordered layout and much like VerticalLayout. Fordescription of margins, spacing, and other features in ordered layouts, see Secção 6.3,“VerticalLayout and HorizontalLayout”.

The following example shows typical use of FormLayout in a form:

// A FormLayout used outside the context of a FormFormLayout fl = new FormLayout();

// Make the FormLayout shrink to its contents fl.setSizeUndefined();

TextField tf = new TextField("A Field");fl.addComponent(tf);

// Mark the first field as requiredtf.setRequired(true);tf.setRequiredError("The Field may not be empty.");

TextField tf2 = new TextField("Another Field");

227FormLayout

Managing Layout

Page 230: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

fl.addComponent(tf2);

// Set the second field straing to error state with a message.tf2.setComponentError( new UserError("This is the error indicator of a Field."));

The resulting layout will look as follows. The error message shows in a tooptip when you hoverthe mouse pointer over the error indicator.

Figura 6.6. A FormLayout Layout for Forms

6.5.1. CSS Style Rules

.v-formlayout {}

.v-formlayout .v-caption {}

/* Columns in a field row. */.v-formlayout-contentcell {} /* Field content. */.v-formlayout-captioncell {} /* Field caption. */.v-formlayout-errorcell {} /* Field error indicator. */

/* Overall style of field rows. */.v-formlayout-row {}.v-formlayout-firstrow {}.v-formlayout-lastrow {}

/* Required field indicator. */.v-formlayout .v-required-field-indicator {}.v-formlayout-captioncell .v-caption .v-required-field-indicator {}

/* Error indicator. */.v-formlayout-cell .v-errorindicator {}.v-formlayout-error-indicator .v-errorindicator {}

The top-level element of FormLayout has the v-formlayout style. The layout is tabular withthree columns: the caption column, the error indicator column, and the field column. These canbe styled with v-formlayout-captioncell, v-formlayout-errorcell, andv-formlayout-contentcell, respectively. While the error indicator is shown as a dedicatedcolumn, the indicator for required fields is currently shown as a part of the caption column.

For information on setting margins and spacing, see also Secção 6.3.1, “Spacing in OrderedLayouts” and Secção 6.13.5, “Layout Margins”.

CSS Style Rules228

Managing Layout

Page 231: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.6. Panel

Panel is a single-component container with a frame around the content. It has an optional captionand an icon which are handled by the panel itself, not its containing layout. The panel itself doesnot manage the caption of its contained component. You need to set the content withsetContent().

Panel has 100% width and undefined height by default. This corresponds with the default sizingof VerticalLayout, which is perhaps most commonly used as the content of a Panel. If the widthor height of a panel is undefined, the content must have a corresponding undefined or fixed sizein the same direction to avoid a sizing paradox.

Panel panel = new Panel("Astronomy Panel");panel.addStyleName("mypanelexample");panel.setSizeUndefined(); // Shrink to fit contentlayout.addComponent(panel);

// Create the contentFormLayout content = new FormLayout();content.addStyleName("mypanelcontent");content.addComponent(new TextField("Participant"));content.addComponent(new TextField("Organization"));content.setSizeUndefined(); // Shrink to fitcontent.setMargin(true);panel.setContent(content);

The resulting layout is shown in Figura 6.7, “A Panel”.

Figura 6.7. A Panel

6.6.1. Scrolling the Panel Content

Normally, if a panel has undefined size in a direction, as it has by default vertically, it will fit thesize of the content and grow as the content grows. However, if it has a fixed or percentual sizeand its content becomes too big to fit in the content area, a scroll bar will appear for the particulardirection. Scroll bars in a Panel are handled natively by the browser with the overflow: autoproperty in CSS.

In the following example, we have a 300 pixels wide and very high Image component as thepanel content.

// Display an image stored in themeImage image = new Image(null, new ThemeResource("img/Ripley_Scroll-300px.jpg"));

// To enable scrollbars, the size of the panel content// must not be relative to the panel sizeimage.setSizeUndefined(); // Actually the default

229Panel

Managing Layout

Page 232: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// The panel will give it scrollbars.Panel panel = new Panel("Scroll");panel.setWidth("300px");panel.setHeight("300px");panel.setContent(image);

layout.addComponent(panel);

The result is shown in Figura 6.8, “Panel with Scroll Bars”. Notice that also the horizontal scrollbarhas appeared even though the panel has the same width as the content (300 pixels) - the 300pxwidth for the panel includes the panel border and vertical scrollbar.

Figura 6.8. Panel with Scroll Bars

Programmatic Scrolling

Panel implements the Scrollable interface to allow programmatic scrolling. You can set thescroll position in pixels with setScrollTop() and setScrollLeft(). You can also get thescroll position set previously, but scrolling the panel in the browser does not update the scrollposition to the server-side.

6.6.1. CSS Style Rules

.v-panel {}

.v-panel-caption {}

.v-panel-nocaption {}

.v-panel-content {}

.v-panel-deco {}

The entire panel has v-panel style. A panel consists of three parts: the caption, content, andbottom decorations (shadow).These can be styled with v-panel-caption, v-panel-content,and v-panel-deco, respectively. If the panel has no caption, the caption element will have thestyle v-panel-nocaption.

CSS Style Rules230

Managing Layout

Page 233: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The built-in light style in the Reindeer and Runo themes has no borders or border decorationsfor the Panel. You can use the Reindeer.PANEL_LIGHT and Runo.PANEL_LIGHT constantsto add the style to a panel. Other themes may also provide the light and other styles for Panelas well.

6.7. Sub-Windows

Sub-windows are floating panels within a native browser window. Unlike native browser windows,sub-windows are managed by the client-side runtime of Vaadin using HTML features. Vaadinallows opening, closing, resizing, maximizing and restoring sub-windows, as well as scrolling thewindow content.

Figura 6.9. A Sub-Window

Sub-windows are typically used for Dialog Windows and Multiple Document Interface applications.Sub-windows are by default not modal; you can set them modal as described in Secção 6.7.4,“Modal Sub-Windows”.

6.7.1. Opening and Closing Sub-Windows

You can open a new sub-window by creating a new Window object and adding it to the UI withaddWindow(), typically in some event listener. A sub-window needs a content component, whichis typically a layout.

In the following, we display a sub-window immediately when a UI opens:

public static class SubWindowUI extends UI { @Override protected void init(VaadinRequest request) { // Some other UI content setContent(new Label("Here's my UI"));

// Create a sub-window and set the content Window subWindow = new Window("Sub-window"); VerticalLayout subContent = new VerticalLayout(); subContent.setMargin(true); subWindow.setContent(subContent);

231Sub-Windows

Managing Layout

Page 234: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Put some components in it subContent.addComponent(new Label("Meatball sub")); subContent.addComponent(new Button("Awlright"));

// Center it in the browser window subWindow.center();

// Open it in the UI addWindow(subWindow); }}

The result was shown in Figura 6.9, “A Sub-Window”. Sub-windows by default have undefinedsize in both dimensions, so they will shrink to fit the content.

The user can close a sub-window by clicking the close button in the upper-right corner of thewindow. The button is controlled by the closable property, so you can disable it withsetClosable(false).

You close a sub-window also programmatically by calling the close() for the sub-window,typically in a click listener for an OK or Cancel button. You can also call removeWindow() forthe current UI.

Sub-Window Management

Usually, you would extend the Window class for your specific sub-window as follows:

// Define a sub-window by inheritanceclass MySub extends Window { public MySub() { super("Subs on Sale"); // Set window caption center();

// Some basic content for the window VerticalLayout content = new VerticalLayout(); content.addComponent(new Label("Just say it's OK!")); content.setMargin(true); setContent(content);

// Disable the close button setClosable(false);

// Trivial logic for closing the sub-window Button ok = new Button("OK"); ok.addClickListener(new ClickListener() { public void buttonClick(ClickEvent event) { close(); // Close the sub-window } }); content.addComponent(ok); }}

You could open the window as follows:

// Some UI logic to open the sub-windowfinal Button open = new Button("Open Sub-Window");open.addClickListener(new ClickListener() {

Opening and Closing Sub-Windows232

Managing Layout

Page 235: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

public void buttonClick(ClickEvent event) { MySub sub = new MySub();

// Add it to the root component UI.getCurrent().addWindow(sub); }});

6.7.2. Window Positioning

When created, a sub-window will have an undefined default size and position. You can specifythe size of a window with setHeight() and setWidth() methods. You can set the positionof the window with setPositionX() and setPositionY() methods.

// Create a new sub-windowmywindow = new Window("My Dialog");

// Set window size.mywindow.setHeight("200px");mywindow.setWidth("400px");

// Set window position.mywindow.setPositionX(200);mywindow.setPositionY(50);

UI.getCurrent().addWindow(mywindow);

6.7.3. Scrolling Sub-Window Content

If a sub-window has a fixed or percentual size and its content becomes too big to fit in the contentarea, a scroll bar will appear for the particular direction. On the other hand, if the sub-windowhas undefined size in the direction, it will fit the size of the content and never get a scroll bar.Scroll bars in sub-windows are handled with regular HTML features, namely overflow: autoproperty in CSS.

As Window extends Panel, windows are also Scrollable. Note that the interface definesprogrammatic scrolling, not scrolling by the user. Please see Secção 6.6, “Panel”.

6.7.4. Modal Sub-Windows

A modal window is a sub-window that prevents interaction with the other UI. Dialog windows, asillustrated in Figura 6.10, “Modal Sub-Window”, are typical cases of modal windows.The advantageof modal windows is limiting the scope of user interaction to a sub-task, so changes in applicationstate are more limited. The disadvantage of modal windows is that they can restrict workflow toomuch.

You can make a sub-window modal with setModal(true).

233Window Positioning

Managing Layout

Page 236: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 6.10. Modal Sub-Window

Depending on the theme, the parent window may be grayed when the modal window is open.

Security Warning

Modality of child windows is purely a client-side feature and can be circumventedwith client-side attack code. You should not trust in the modality of child windows insecurity-critical situations such as login windows.

6.8. HorizontalSplitPanel and VerticalSplitPanel

HorizontalSplitPanel and VerticalSplitPanel are a two-component containers that divide theavailable space into two areas to accomodate the two components. HorizontalSplitPanel makesthe split horizontally with a vertical splitter bar, and VerticalSplitPanel vertically with a horizontalsplitter bar. The user can drag the bar to adjust its position.

You can set the two components with the setFirstComponent() andsetSecondComponent() methods, or with the regular addComponent() method.

// Have a panel to put stuff inPanel panel = new Panel("Split Panels Inside This Panel");

// Have a horizontal split panel as its contentHorizontalSplitPanel hsplit = new HorizontalSplitPanel();panel.setContent(hsplit);

// Put a component in the left panelTree tree = new Tree("Menu", TreeExample.createTreeContent());hsplit.setFirstComponent(tree);

// Put a vertical split panel in the right panelVerticalSplitPanel vsplit = new VerticalSplitPanel();hsplit.setSecondComponent(vsplit);

HorizontalSplitPanel and VerticalSplitPanel234

Managing Layout

Page 237: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Put other components in the right panelvsplit.addComponent(new Label("Here's the upper panel"));vsplit.addComponent(new Label("Here's the lower panel"));

The result is shown in Figura 6.11, “HorizontalSplitPanel and VerticalSplitPanel”. Observethat the tree is cut horizontally as it can not fit in the layout. If its height exceeds the height of thepanel, a vertical scroll bar will appear automatically. If horizontal scroll bar is necessary, youcould put the content in a Panel, which can have scroll bars in both directions.

Figura 6.11. HorizontalSplitPanel and VerticalSplitPanel

You can set the split position with setSplitPosition(). It accepts any units defined in theSizeable interface, with percentual size relative to the size of the component.

// Have a horizontal split panelHorizontalSplitPanel hsplit = new HorizontalSplitPanel();hsplit.setFirstComponent(new Label("75% wide panel"));hsplit.setSecondComponent(new Label("25% wide panel"));

// Set the position of the splitter as percentagehsplit.setSplitPosition(75, Sizeable.UNITS_PERCENTAGE);

Another version of the setSplitPosition() method allows leaving out the unit, using thesame unit as previously.The method also has versions take take a boolean parameter, reverse,which allows defining the size of the right or bottom panel instead of the left or top panel.

The split bar allows the user to adjust the split position by dragging the bar with mouse. To lockthe split bar, use setLocked(true). When locked, the move handle in the middle of the bar isdisabled.

// Lock the splitterhsplit.setLocked(true);

Setting the split position programmatically and locking the split bar is illustrated in Figura 6.12,“A Layout With Nested SplitPanels”.

235HorizontalSplitPanel and VerticalSplitPanel

Managing Layout

Page 238: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 6.12. A Layout With Nested SplitPanels

Notice that the size of a split panel must not be undefined in the split direction.

6.8.1. CSS Style Rules

/* For a horizontal SplitPanel. */.v-splitpanel-horizontal {}.v-splitpanel-hsplitter {}.v-splitpanel-hsplitter-locked {}

/* For a vertical SplitPanel. */.v-splitpanel-vertical {}.v-splitpanel-vsplitter {}.v-splitpanel-vsplitter-locked {}

/* The two container panels. */.v-splitpanel-first-container {} /* Top or left panel. */.v-splitpanel-second-container {} /* Bottom or right panel. */

The entire split panel has the style v-splitpanel-horizontal or v-splitpanel-vertical,depending on the panel direction. The split bar or splitter between the two content panels haseither the ...-splitter or ...-splitter-locked style, depending on whether its positionis locked or not.

6.9. TabSheet

The TabSheet is a multicomponent container that allows switching between the componentswith "tabs". The tabs are organized as a tab bar at the top of the tab sheet. Clicking on a tabopens its contained component in the main display area of the layout. If there are more tabs thanfit in the tab bar, navigation buttons will appear.

CSS Style Rules236

Managing Layout

Page 239: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 6.13. A Simple TabSheet Layout

6.9.1. Adding Tabs

You add new tabs to a tab sheet with the addTab() method. The simple version of the methodtakes as its parameter the root component of the tab.You can use the root component to retrieveits corresponding Tab object. Typically, you put a layout component as the root component.

You can also give the caption and the icon as parameters for the addTab() method.The followingexample demonstrates the creation of a simple tab sheet, where each tab shows a different Labelcomponent. The tabs have an icon, which are (in this example) loaded as Java class loaderresources from the application.

TabSheet tabsheet = new TabSheet();layout.addComponent(tabsheet);

// Create the first tabVerticalLayout tab1 = new VerticalLayout();tab1.addComponent(new Embedded(null, new ThemeResource("img/planets/Mercury.jpg")));tabsheet.addTab(tab1, "Mercury", new ThemeResource("img/planets/Mercury_symbol.png"));

// This tab gets its caption from the component captionVerticalLayout tab2 = new VerticalLayout();tab2.addComponent(new Embedded(null, new ThemeResource("img/planets/Venus.jpg")));tab2.setCaption("Venus");tabsheet.addTab(tab2).setIcon( new ThemeResource("img/planets/Venus_symbol.png"));...

6.9.2.Tab Objects

Each tab in a tab sheet is represented as a Tab object, which manages the tab caption, icon,and attributes such as hidden and visible.You can set the caption with setCaption() and theicon with setIcon(). If the component added with addTab() has a caption or icon, it is used

237Adding Tabs

Managing Layout

Page 240: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

as the default for the Tab object. However, changing the attributes of the root component laterdoes not affect the tab, but you must make the setting through the Tab object. The addTab()returns the new Tab object, so you can easily set an attribute using the reference.

// Set an attribute using the returned referencetabsheet.addTab(myTab).setCaption("My Tab");

Disabling and Hiding Tabs

A tab can be disabled by setting setEnabled(false) for the Tab object, thereby disallowingselecting it.

A tab can be made invisible by setting setVisible(false) for the Tab object.The hideTabs()method allows hiding the tab bar entirely.This can be useful in tabbed document interfaces (TDI)when there is only one tab.

Figura 6.14. A TabSheet with Hidden and Disabled Tabs

6.9.3.Tab Change Events

Clicking on a tab selects it. This fires a TabSheet.SelectedTabChangeEvent, which you canhandle by implementing the TabSheet.SelectedTabChangeListener interface.You can accessthe tabsheet of the event with getTabSheet(), and find the new selected tab withgetSelectedTab().

You can programmatically select a tab with setSelectedTab(), which also fires theSelectedTabChangeEvent (beware of recursive events). Reselecting the currently selected tabdoes not fire the event.

Notice that when the first tab is added, it is selected and the change event is fired, so if you wantto catch that, you need to add your listener before adding any tabs.

Creating Tab Content Dynamically

In the following example, we create the tabs as empty content layouts, and add the tab contentdynamically when a tab is selected:

TabSheet tabsheet = new TabSheet();

// Create tab content dynamically when tab is selectedtabsheet.addSelectedTabChangeListener( new TabSheet.SelectedTabChangeListener() { public void selectedTabChange(SelectedTabChangeEvent event) { // Find the tabsheet TabSheet tabsheet = event.getTabSheet();

// Find the tab (here we know it's a layout) Layout tab = (Layout) tabsheet.getSelectedTab();

// Get the tab caption from the tab object String caption = tabsheet.getTab(tab).getCaption();

Tab Change Events238

Managing Layout

Page 241: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Fill the tab content tab.removeAllComponents(); tab.addComponent(new Image(null, new ThemeResource("img/planets/"+caption+".jpg"))); }});

// Have some tabsString[] tabs = {"Mercury", "Venus", "Earth", "Mars"};for (String caption: tabs) tabsheet.addTab(new VerticalLayout(), caption, new ThemeResource("img/planets/"+caption+"_symbol.png"));

6.9.4. Enabling and Handling Closing Tabs

You can enable a close button for individual tabs with the closable property in the TabSheet.Tabobjects.

// Enable closing the tabtabsheet.getTab(tabComponent).setClosable(true);

Figura 6.15.TabSheet with Closable Tabs

Handling Tab Close Events

You can handle closing tabs by implementing a custom TabSheet.CloseHandler. The defaultimplementation simply calls removeTab() for the tab to be closed, but you can prevent the closeby not calling it. This allows, for example, opening a dialog window to confirm the close.

tabsheet.setCloseHandler(new CloseHandler() { @Override public void onTabClose(TabSheet tabsheet, Component tabContent) { Tab tab = tabsheet.getTab(tabContent); Notification.show("Closing " + tab.getCaption());

// We need to close it explicitly in the handler tabsheet.removeTab(tab); }});

6.9.1. CSS Style Rules

.v-tabsheet {}

.v-tabsheet-tabs {}

.v-tabsheet-content {}

.v-tabsheet-deco {}

.v-tabsheet-tabcontainer {}

.v-tabsheet-tabsheetpanel {}

239Enabling and Handling Closing Tabs

Managing Layout

Page 242: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

.v-tabsheet-hidetabs {}

.v-tabsheet-scroller {}

.v-tabsheet-scrollerPrev {}

.v-tabsheet-scrollerNext {}

.v-tabsheet-scrollerPrev-disabled{}

.v-tabsheet-scrollerNext-disabled{}

.v-tabsheet-tabitem {}

.v-tabsheet-tabitem-selected {}

.v-tabsheet-tabitemcell {}

.v-tabsheet-tabitemcell-first {}

.v-tabsheet-tabs td {}

.v-tabsheet-spacertd {}

The entire tabsheet has the v-tabsheet style. A tabsheet consists of three main parts: the tabson the top, the main content pane, and decorations around the tabsheet.

The tabs area at the top can be styled with v-tabsheet-tabs, v-tabsheet-tabcontainerand v-tabsheet-tabitem*.

The style v-tabsheet-spacertd is used for any empty space after the tabs. If the tabsheethas too little space to show all tabs, scroller buttons enable browsing the full tab list. These usethe styles v-tabsheet-scroller*.

The content area where the tab contents are shown can be styled with v-tabsheet-content,and the surrounding decoration with v-tabsheet-deco.

6.10. Accordion

Accordion is a multicomponent container similar to TabSheet, except that the "tabs" are arrangedvertically. Clicking on a tab opens its contained component in the space between the tab and thenext one. You can use an Accordion identically to a TabSheet, which it actually inherits. SeeSecção 6.9, “TabSheet” for more information.

The following example shows how you can create a simple accordion. As the Accordion is rathernaked alone, we put it inside a Panel that acts as its caption and provides it a border.

// Create the Accordion.Accordion accordion = new Accordion();

// Have it take all space available in the layout.accordion.setSizeFull();

// Some components to put in the Accordion.Label l1 = new Label("There are no previously saved actions.");Label l2 = new Label("There are no saved notes.");Label l3 = new Label("There are currently no issues.");

// Add the components as tabs in the Accordion.accordion.addTab(l1, "Saved actions", null);accordion.addTab(l2, "Notes", null);accordion.addTab(l3, "Issues", null);

// A container for the Accordion.Panel panel = new Panel("Tasks");panel.setWidth("300px");

Accordion240

Managing Layout

Page 243: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

panel.setHeight("300px");panel.setContent(accordion);

// Trim its layout to allow the Accordion take all space.panel.getLayout().setSizeFull();panel.getLayout().setMargin(false);

Figura 6.16, “An Accordion” shows what the example would look like with the default theme.

Figura 6.16. An Accordion

6.10.1. CSS Style Rules

.v-accordion {}

.v-accordion-item {}

.v-accordion-item-open {}

.v-accordion-item-first {}

.v-accordion-item-caption {}

.v-accordion-item-caption .v-caption {}

.v-accordion-item-content {}

The top-level element of Accordion has the v-accordion style. An Accordion consists of asequence of item elements, each of which has a caption element (the tab) and a content areaelement.

The selected item (tab) has also the v-accordion-open style. The content area is not shownfor the closed items.

6.11. AbsoluteLayout

AbsoluteLayout allows placing components in arbitrary positions in the layout area.The positionsare specified in the addComponent() method with horizontal and vertical coordinates relativeto an edge of the layout area. The positions can include a third depth dimension, the z-index,which specifies which components are displayed in front and which behind other components.

The positions are specified by a CSS absolute position string, using the left, right, top,bottom, and z-index properties known from CSS. In the following example, we have a 300 by150 pixels large layout and position a text field 50 pixels from both the left and the top edge:

241CSS Style Rules

Managing Layout

Page 244: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// A 400x250 pixels size layoutAbsoluteLayout layout = new AbsoluteLayout();layout.setWidth("400px");layout.setHeight("250px");

// A component with coordinates for its top-left cornerTextField text = new TextField("Somewhere someplace");layout.addComponent(text, "left: 50px; top: 50px;");

The left and top specify the distance from the left and top edge, respectively. The right andbottom specify the distances from the right and top edge.

// At the top-left cornerButton button = new Button( "left: 0px; top: 0px;");layout.addComponent(button, "left: 0px; top: 0px;");

// At the bottom-right cornerButton buttCorner = new Button( "right: 0px; bottom: 0px;");layout.addComponent(buttCorner, "right: 0px; bottom: 0px;");

// Relative to the bottom-right cornerButton buttBrRelative = new Button( "right: 50px; bottom: 50px;");layout.addComponent(buttBrRelative, "right: 50px; bottom: 50px;");

// On the bottom, relative to the left sideButton buttBottom = new Button( "left: 50px; bottom: 0px;");layout.addComponent(buttBottom, "left: 50px; bottom: 0px;");

// On the right side, up from the bottomButton buttRight = new Button( "right: 0px; bottom: 100px;");layout.addComponent(buttRight, "right: 0px; bottom: 100px;");

The result of the above code examples is shown in Figura 6.17, “Components Positioned Relativeto Various Edges”.

Figura 6.17. Components Positioned Relative to Various Edges

In the above examples, we had components of undefined size and specified the positions ofcomponents by a single pair of coordinates. The other possibility is to specify an area and let thecomponent fill the area by specifying a proportinal size for the component, such as "100%".Normally, you use setSizeFull() to take the entire area given by the layout.

AbsoluteLayout242

Managing Layout

Page 245: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Specify an area that a component should fillPanel panel = new Panel("A Panel filling an area");panel.setSizeFull(); // Fill the entire given arealayout.addComponent(panel, "left: 25px; right: 50px; "+ "top: 100px; bottom: 50px;");

The result is shown in Figura 6.18, “Component Filling an Area Specified by Coordinates”

Figura 6.18. Component Filling an Area Specified by Coordinates

You can also use proportional coordinates to specify the coordinates:

// A panel that takes 30% to 90% horizontally and// 20% to 80% verticallyPanel panel = new Panel("A Panel");panel.setSizeFull(); // Fill the specified arealayout.addComponent(panel, "left: 30%; right: 10%;" + "top: 20%; bottom: 20%;");

The result is shown in Figura 6.19, “Specifying an Area by Proportional Coordinates”

Figura 6.19. Specifying an Area by Proportional Coordinates

Drag and drop is very useful for moving the components contained in an AbsoluteLayout. Checkout the example in Secção 11.12.6, “Dropping on a Component”.

243AbsoluteLayout

Managing Layout

Page 246: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.11.1. Styling with CSS

.v-absolutelayout {}

.v-absolutelayout-wrapper {}

The AbsoluteLayout component has v-absolutelayout root style. Each component in thelayout is contained within an element that has the v-absolutelayout-wrapper.The componentcaptions are outside the wrapper elements, in a separate element with the usual v-captionstyle.

6.12. CssLayout

CssLayout allows strong control over styling of the components contained inside the layout.Thecomponents are contained in a simple DOM structure consisting of <div> elements. By default,the contained components are laid out horizontally and wrap naturally when they reach the widthof the layout, but you can control this and most other behaviour with CSS. You can also injectcustom CSS for each contained component. As CssLayout has a very simple DOM structureand no dynamic rendering logic, relying purely on the built-in rendering logic of the browsers, itis the fastest of the layout components.

The basic use of CssLayout is just like with any other layout component:

CssLayout layout = new CssLayout();

// Component with a layout-managed caption and iconTextField tf = new TextField("A TextField");tf.setIcon(new ThemeResource("icons/user.png"));layout.addComponent(tf);

// Labels are 100% wide by default so must unset widthLabel label = new Label("A Label");label.setWidth(Sizeable.SIZE_UNDEFINED, 0);layout.addComponent(label);

layout.addComponent(new Button("A Button"));

The result is shown in Figura 6.20, “Basic Use of CssLayout”. Notice that the default spacingand alignment of the layout is quite crude and CSS styling is nearly always needed.

Figura 6.20. Basic Use of CssLayout

The display attribute of CssLayout is inline-block by default, so the components are laidout horizontally following another. CssLayout has 100% width by default. If the componentsreach the width of the layout, they are wrapped to the next "line" just as text would be. If you adda component with 100% width, it will take an entire line by wrapping before and after thecomponent.

6.12.1. CSS Injection

Overriding the getCss() method allows injecting custom CSS for each component. The CSSreturned by the method is inserted in the style attribute of the <div> element of the component,so it will override any style definitions made in CSS files.

Styling with CSS244

Managing Layout

Page 247: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

CssLayout layout = new CssLayout() { @Override protected String getCss(Component c) { if (c instanceof Label) { // Color the boxes with random colors int rgb = (int) (Math.random()*(1<<24)); return "background: #" + Integer.toHexString(rgb); } return null; }};layout.setWidth("400px"); // Causes to wrap the contents

// Add boxes of various sizesfor (int i=0; i<40; i++) { Label box = new Label("&nbsp;", Label.CONTENT_XHTML); box.addStyleName("flowbox"); box.setWidth((float) Math.random()*50, Sizeable.UNITS_PIXELS); box.setHeight((float) Math.random()*50, Sizeable.UNITS_PIXELS); layout.addComponent(box);}

The style name added to the components allows making common styling in a CSS file:

.v-label-flowbox { border: thin black solid;}

Figura 6.21, “Use of getCss() and line wrap” shows the rendered result.

Figura 6.21. Use of getCss() and line wrap

6.12.2. Browser Compatibility

The stregth of the CssLayout is also its weakness. Much of the logic behind the other layoutcomponents is there to give nice default behaviour and to handle the differences in differentbrowsers. Some browsers, no need to say which, are notoriously incompatible with the CSSstandards, so they require a lot of custom CSS. You may need to make use of the browser-specific style classes in the root element of the application. Some features in the other layoutsare not even solvable in pure CSS, at least in all browsers.

245Browser Compatibility

Managing Layout

Page 248: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

6.12.1. Styling with CSS

.v-csslayout {}

.v-csslayout-margin {}

.v-csslayout-container {}

The CssLayout component has v-csslayout root style. The margin element withv-csslayout-margin style is always enabled. The components are contained in an elementwith v-csslayout-container style.

For example, we could style the basic CssLayout example shown earlier as follows:

/* Have the caption right of the text box, bottom-aligned */.csslayoutexample .mylayout .v-csslayout-container { direction: rtl; line-height: 24px; vertical-align: bottom;}

/* Have some space before and after the caption */.csslayoutexample .mylayout .v-csslayout-container .v-caption { padding-left: 3px; padding-right: 10px;}

The example would now be rendered as shown in Figura 6.22, “Styling CssLayout”.

Figura 6.22. Styling CssLayout

Captions and icons that are managed by the layout are contained in an element with v-captionstyle. These caption elements are contained flat at the same level as the actual componentelements. This may cause problems with wrapping in inline-block mode, as wrapping canoccur between the caption and its corresponding component element just as well as betweencomponents. Such use case is therefore not feasible.

6.13. Layout Formatting

While the formatting of layouts is mainly done with style sheets, just as with other components,style sheets are not ideal or even possible to use in some situations. For example, CSS doesnot allow defining the spacing of table cells, which is done with the cellspacing attribute inHTML.

Moreover, as many layout sizes are calculated dynamically in the Client-Side Engine of Vaadin,some CSS settings can fail altogether.

6.13.1. Layout Size

The size of a layout component can be specified with the setWidth() and setHeight()methods defined in the Sizeable interface, just like for any component. It can also be undefined,in which case the layout shrinks to fit the component(s) inside it. Secção 5.3.9, “SizingComponents” gives details on the interface.

Styling with CSS246

Managing Layout

Page 249: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 6.23. HorizontalLayout with Undefined vs Defined size

Many layout components take 100% width by default, while they have the height undefined.

The sizes of components inside a layout can also be defined as a percentage of the spaceavailable in the layout, for example with setWidth("100%"); or with the (most commonly usedmethod) setFullSize() that sets 100% size in both directions. If you use a percentage in aHorizontalLayout, VerticalLayout, or GridLayout, you will also have to set the component asexpanding, as noted below.

Atenção

A layout that contains components with percentual size must have a defined size!

If a layout has undefined size and a contained component has, say, 100% size, thecomponent will try to fill the space given by the layout, while the layout will shrink tofit the space taken by the component, which is a paradox. This requirement holdsfor height and width separately.The debug mode allows detecting such invalid cases;see Secção 11.3.5, “Inspecting Component Hierarchy”.

For example:

// This takes 100% width but has undefined height.VerticalLayout layout = new VerticalLayout();

// A button that takes all the space available in the layout.Button button = new Button("100%x100% button");button.setSizeFull();layout.addComponent(button);

// We must set the layout to a defined height vertically, in// this case 100% of its parent layout, which also must// not have undefined size.layout.setHeight("100%");

If you have a layout with undefined height, such as VerticalLayout, in a UI, Window, or Panel,and put enough content in it so that it extends outside the bottom of the view area, scrollbars willappear. If you want your application to use all the browser view, nothing more or less, you shoulduse setFullSize() for the root layout.

// Create the UI contentVerticalLayout content = new VerticalLayout();

// Use entire view areacontent.setSizeFull();

setContent(content);

6.13.2. Expanding Components

If you set a HorizontalLayout to a defined size horizontally or a VerticalLayout vertically, andthere is space left over from the contained components, the extra space is distributed equally

247Expanding Components

Managing Layout

Page 250: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

between the component cells. The components are aligned within these cells, according to theiralignment setting, top left by default, as in the example below.

Often, you don't want such empty space, but want one or more components to take all the leftoverspace. You need to set such a component to 100% size and use setExpandRatio(). If thereis just one such expanding component in the layout, the ratio parameter is irrelevant.

If you set multiple components as expanding, the expand ratio dictates how large proportion ofthe available space (overall or excess depending on whether the components are sized as apercentage or not) each component takes. In the example below, the buttons have 1:2:3 ratiofor the expansion.

GridLayout has corresponding method for both of its directions, setRowExpandRatio() andsetColumnExpandRatio().

Expansion is dealt in detail in the documentation of the layout components that support it. SeeSecção 6.3, “VerticalLayout and HorizontalLayout” and Secção 6.4, “GridLayout” for detailson components with relative sizes.

6.13.3. Layout Cell Alignment

You can set the alignment of the component inside a specific layout cell with thesetComponentAlignment() method. The method takes as its parameters the componentcontained in the cell to be formatted, and the horizontal and vertical alignment.

Figura 6.24, “Cell Alignments” illustrates the alignment of components within a GridLayout.

Figura 6.24. Cell Alignments

The easiest way to set alignments is to use the constants defined in the Alignment class. Letus look how the buttons in the top row of the above GridLayout are aligned with constants:

// Create a grid layoutfinal GridLayout grid = new GridLayout(3, 3);

grid.setWidth(400, Sizeable.UNITS_PIXELS);grid.setHeight(200, Sizeable.UNITS_PIXELS);

Button topleft = new Button("Top Left");grid.addComponent(topleft, 0, 0);grid.setComponentAlignment(topleft, Alignment.TOP_LEFT);

Layout Cell Alignment248

Managing Layout

Page 251: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Button topcenter = new Button("Top Center");grid.addComponent(topcenter, 1, 0);grid.setComponentAlignment(topcenter, Alignment.TOP_CENTER);

Button topright = new Button("Top Right");grid.addComponent(topright, 2, 0);grid.setComponentAlignment(topright, Alignment.TOP_RIGHT);...

The following table lists all the Alignment constants by their respective locations:

Tabela 6.1. Alignment Constants

TOP_RIGHTTOP_CENTERTOP_LEFT

MIDDLE_RIGHTMIDDLE_CENTERMIDDLE_LEFT

BOTTOM_RIGHTBOTTOM_CENTERBOTTOM_LEFT

Another way to specify the alignments is to create an Alignment object and specify the horizontaland vertical alignment with separate constants.You can specify either of the directions, in whichcase the other alignment direction is not modified, or both with a bitmask operation between thetwo directions.

Button middleleft = new Button("Middle Left");grid.addComponent(middleleft, 0, 1);grid.setComponentAlignment(middleleft, new Alignment(Bits.ALIGNMENT_VERTICAL_CENTER | Bits.ALIGNMENT_LEFT));

Button middlecenter = new Button("Middle Center");grid.addComponent(middlecenter, 1, 1);grid.setComponentAlignment(middlecenter, new Alignment(Bits.ALIGNMENT_VERTICAL_CENTER | Bits.ALIGNMENT_HORIZONTAL_CENTER));

Button middleright = new Button("Middle Right");grid.addComponent(middleright, 2, 1);grid.setComponentAlignment(middleright, new Alignment(Bits.ALIGNMENT_VERTICAL_CENTER | Bits.ALIGNMENT_RIGHT));

Obviously, you may combine only one vertical bitmask with one horizontal bitmask, though youmay leave either one out. The following table lists the available alignment bitmask constants:

Tabela 6.2. Alignment Bitmasks

Bits.ALIGNMENT_LEFTHorizontal

Bits.ALIGNMENT_HORIZONTAL_CENTER

Bits.ALIGNMENT_RIGHT

Bits.ALIGNMENT_TOPVertical

Bits.ALIGNMENT_VERTICAL_CENTER

Bits.ALIGNMENT_BOTTOM

249Layout Cell Alignment

Managing Layout

Page 252: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

You can determine the current alignment of a component with getComponentAlignment(),which returns an Alignment object.The class provides a number of getter methods for decodingthe alignment, which you can also get as a bitmask value.

Size of Aligned Components

You can only align a component that is smaller than its containing cell in the direction of alignment.If a component has 100% width, as many components have by default, horizontal alignment doesnot have any effect. For example, Label is 100% wide by default and can not therefore behorizontally aligned as such.The problem can be hard to notice, as the text inside a Label is left-aligned.

You usually need to set either a fixed size, undefined size, or less than a 100% relative size forthe component to be aligned - a size that is smaller than the containing layout has.

For example, assuming that a Label has short content that is less wide than the containingVerticalLayout, you could center it as follows:

VerticalLayout layout = new VerticalLayout(); // 100% default widthLabel label = new Label("Hello"); // 100% default widthlabel.setSizeUndefined();layout.addComponent(label);layout.setComponentAlignment(label, Alignment.MIDDLE_CENTER);

If you set the size as undefined and the component itself contains components, make sure thatthe contained components also have either undefined or fixed size. For example, if you set thesize of a Form as undefined, its containing layout FormLayout has 100% default width, whichyou also need to set as undefined. But then, any components inside the FormLayout must haveeither undefined or fixed size.

6.13.4. Layout Cell Spacing

The VerticalLayout, HorizontalLayout, and GridLayout layouts offer a setSpacing() methodto enable spacing between the cells of the layout.

For example:

VerticalLayout layout = new VerticalLayout();layout.setSpacing(true);layout.addComponent(new Button("Component 1"));layout.addComponent(new Button("Component 2"));layout.addComponent(new Button("Component 3"));

The effect of spacing in VerticalLayout and HorizontalLayout is illustrated in Figura 6.25,“Layout Spacings”.

Figura 6.25. Layout Spacings

Layout Cell Spacing250

Managing Layout

Page 253: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The exact amount of spacing is defined in CSS. If the default is not suitable, you can customizeit in a custom theme. Spacing is implemented in a bit different ways in different layouts. In theordered layouts, it is done with spacer elements, while in the GridLayout it has special handling.Please see the sections on the individual components for more details.

6.13.5. Layout Margins

Most layout components do not have any margin around them by default. The ordered layouts,as well as GridLayout, support enabling a margin with setMargin().This enables CSS classesfor each margin in the HTML element of the layout component.To customize the default margins,you can define each margin with the padding property in CSS.

You may want to have a custom CSS class for the layout component to enable specificcustomization of the margins, as is done in the following with the mymargins class:

.mymargins.v-margin-left {padding-left: 10px;}

.mymargins.v-margin-right {padding-right: 20px;}

.mymargins.v-margin-top {padding-top: 40px;}

.mymargins.v-margin-bottom {padding-bottom: 80px;}

You can enable only specific margins by passing a MarginInfo to the setMargin().The marginsare specified in clockwise order for top, right, bottom, and left margin.The following would enablethe left and right margins:

layout.setMargin(new MarginInfo(false, true, false, true));

The resulting margins are shown in Figura 6.26, “Layout Margins” below. The two ways produceidentical margins.

Figura 6.26. Layout Margins

6.14. Custom Layouts

While it is possible to create almost any typical layout with the standard layout components, it issometimes best to separate the layout completely from code.With the CustomLayout component,you can write your layout as a template in XHTML that provides locations of any containedcomponents. The layout template is included in a theme. This separation allows the layout to bedesigned separately from code, for example using WYSIWYG web designer tools such as AdobeDreamweaver.

251Layout Margins

Managing Layout

Page 254: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

A template is a HTML file located under layouts folder under a theme folder under theWebContent/VAADIN/themes/ f o l d e r , f o r e x a m p l e ,WebContent/VAADIN/themes/themename/layouts/mylayout.html. (Notice that theroot path WebContent/VAADIN/themes/ for themes is fixed.) A template can also be provideddynamically from an InputStream, as explained below. A template includes <div> elementswith a location attribute that defines the location identifier. All custom layout HTML-files mustbe saved using UTF-8 character encoding.

<table width="100%" height="100%"> <tr height="100%"> <td> <table align="center"> <tr> <td align="right">User&nbsp;name:</td> <td><div location="username"></div></td> </tr> <tr> <td align="right">Password:</td> <td><div location="password"></div></td> </tr> </table> </td> </tr> <tr> <td align="right" colspan="2">

<div location="okbutton"></div> </td> </tr></table>

The client-side engine of Vaadin will replace contents of the location elements with thecomponents. The components are bound to the location elements by the location identifier givento addComponent(), as shown in the example below.

// Have a Panel where to put the custom layout.Panel panel = new Panel("Login");panel.setSizeUndefined();main.addComponent(panel);

// Create custom layout from "layoutname.html" template.CustomLayout custom = new CustomLayout("layoutname");custom.addStyleName("customlayoutexample");

// Use it as the layout of the Panel.panel.setContent(custom);

// Create a few components and bind them to the location tags// in the custom layout.TextField username = new TextField();custom.addComponent(username, "username");

TextField password = new TextField();custom.addComponent(password, "password");

Button ok = new Button("Login");custom.addComponent(ok, "okbutton");

The resulting layout is shown below in Figura 6.27, “Example of a Custom Layout Component”.

Custom Layouts252

Managing Layout

Page 255: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 6.27. Example of a Custom Layout Component

You can use addComponent() also to replace an existing component in the location given inthe second parameter.

In addition to a static template file, you can provide a template dynamically with the CustomLayoutconstructor that accepts an InputStream as the template source. For example:

new CustomLayout(new ByteArrayInputStream("<b>Template</b>".getBytes()));

or

new CustomLayout(new FileInputStream(file));

253Custom Layouts

Managing Layout

Page 256: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

254

Page 257: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 7

Visual UserInterface Design

with Eclipse

7.1. Overview ................................................................................................ 2557.2. Creating a New Composite .................................................................... 2577.3. Using The Visual Editor ......................................................................... 2597.4. Structure of a Visually Editable Component .......................................... 264

This chapter provides instructions for developing the graphical user interface of Vaadin componentswith the Vaadin Plugin for the Eclipse IDE.

7.1. Overview

The visual editor feature in the Vaadin Plugin for Eclipse allows you to design the user interfaceof an entire application or of specific composite components. The plugin generates the actualJava code, which is designed to be reusable, so you can design the basic layout of the userinterface with the visual editor and build the user interaction logic on top of the generated code.You can use inheritance and composition to modify the components further.

The editor works with classes that extend the CustomComponent class, which is the basictechnique in Vaadin for creating composite components. Component composition is described

255Book of Vaadin

Page 258: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

in Secção 5.24, “Component Composition with CustomComponent”. Any CustomComponentwill not do for the visual editor; you need to create a new one as instructed below.

7.1.1. Using a Composite Component

You can use a composite component just as you would use any Vaadin component. However,the composite as well as its root layout, which is an AbsoluteLayout, are full size (100% wideand high) by default. A component with full size (expand-to-fit layout) may not normally be insidea layout with undefined size (shrink-to-fit content). For example, if you put a composite in aVerticalLayout, which has undefined height by default, you have to set the layout explicitly tohave a defined height, either fixed or full (100%) height.

public class MyUI extends UI { @Override protected void init(VaadinRequest request) { // Create the content root layout for the UI VerticalLayout content = new VerticalLayout(); setContent(content);

// Needed because the composites are full size content.setSizeFull();

MyComposite myComposite = new MyComposite(); content.addComponent(myComposite); }}

You could also set the size of the root layout of the composite to a fixed height (in componentproperties in the visual editor). The important thing to notice is that an AbsoluteLayout maynever have undefined size.

7.1.2. Installing the Visual Editor

The visual editor is currently included in the Vaadin Plugin for Eclipse. For its installation, seeSecção 2.4, “Instalando o Plugin Vaadin para Eclipse”.

The editor runs in an internal browser in Eclipse. The actual browser engine used depends onthe operating system. Using the internal browser must be enabled in Window   Preferences  General   Web Browsers.

In Ubuntu 12.04 and some other versions, no embedded browser engine is installed in the systemby default. You can use at least Firefox XULRunner and WebKit. You can install WebKit asfollows:

$ sudo apt-get install libwebkitgtk-1.0-0

Then, restart Eclipse and check that the internal browser is enabled.

Using a Composite Component256

Visual User Interface Design with Eclipse

Page 259: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

7.2. Creating a New Composite

If the Vaadin Plugin is installed in Eclipse, you can create a new composite component as follows.

1. Select File   New   Other... in the main menu or right-click the Project Explorer andselect New   Other... to open the New window.

2. In the first, Select a wizard step, select Vaadin   Vaadin Composite and click Next.

3. The Source folder is the root source directory where the new component will be created.This is by default the default source directory of your project.

257Creating a New Composite

Visual User Interface Design with Eclipse

Page 260: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Enter the Java Package under which the new component class should be created orselect it by clicking the Browse button. Also enter the class Name of the new component.

Finally, click Finish to create the component.

A newly created composite component is opened in the Design window, as shown in Figura 7.1,“New Composite Component”.

Creating a New Composite258

Visual User Interface Design with Eclipse

Page 261: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 7.1. New Composite Component

You can observe that a component that you can edit with the visual editor has two tabs at thebottom of the view: Source and Design. These tabs allow switching between the source viewand the visual design view.

If you later open the source file for editing, the Source and Design tabs should appear belowthe source editor. If they do not, right-click the file in the Project Explorer and select Open With.

7.3. Using The Visual Editor

The visual editor view consists of, on the left side, an editing area that displays the current layoutand, on the right side, a control panel that contains a component list for selecting new componentsto add, the current component tree, and a component property panel.

7.3.1. Adding New Components

Adding new components to the user interface is done as follows by dragging them from thecomponent list to either the editing area or to the component tree. If you drag the componentsto the tree,

1. Select which components are shown in the component list by entering a search stringor by expanding the filters and selecting only the desired component categories.

259Using The Visual Editor

Visual User Interface Design with Eclipse

Page 262: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

2. Drag a component from the component list to either:

a. Editing area, where you can easily move and resize the component. Dragging acomponent onto a layout component will add it in it and you can also positioncomponents within a layout by dragging them.

b. Component tree. Remember that you can only add components under a layoutcomponent or other component container.

3. Edit the component properties

a. In the editing area, you can move and resize the components, and set their alignmentin the containing layout.

b. In the property panel, you can set the component name, size, position and otherproperties.

Figura 7.2. Adding a New Component Node

You can delete a component by right-clicking it in the component tree and selecting Remove.The context menu also allows copying and pasting components.

A composite component created by the plugin must have a AbsoluteLayout as its root layout.While it is suitable for the visual editor, absolute layouts are rarely used otherwise in Vaadinapplications. If you want to use another root layout, you can add another layout inside themainLayout and set that as the root with setCompositionRoot() in the source view. It willbe used as the root when the component is actually used in an application.

7.3.2. Setting Component Properties

The property setting sub-panel of the control panel allows setting component properties. Thepanel has two tabs: Layout and Properties, where the latter defines the various basic properties.

Setting Component Properties260

Visual User Interface Design with Eclipse

Page 263: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Basic Properties

The top section of the property panel, shown in Figura 7.3, “Basic Component Properties”, allowssetting basic component properties. The panel also includes properties such as field propertiesfor field components.

Figura 7.3. Basic Component Properties

The properties are as follows:

NameThe name of the component, which is used for the reference to the component, so itmust obey Java notation for variable names.

Style NameA space-separated list of CSS style class names for the component. See Capítulo 8,Themes for information on component styles in themes.

CaptionThe caption of a component is usually displayed above the component. Somecomponents, such as Button, display the caption inside the component. For Labeltext, you should set the value of the label instead of the caption, which should be leftempty.

Description (tooltip)The description is usually displayed as a tooltip when the mouse pointer hovers overthe component for a while. Some components, such as Form have their own way ofdisplaying the description.

261Setting Component Properties

Visual User Interface Design with Eclipse

Page 264: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

IconThe icon of a component is usually displayed above the component, left of the caption.Some components, such as Button, display the icon inside the component.

Formatting typeSome components allow different formatting types, such as Label, which allowformatting either as Text, XHTML, Preformatted, and Raw.

ValueThe component value.The value type and how it is displayed by the component variesbetween different component types and each value type has its own editor. The editoropens by clicking on the ... button.

Most of the basic component properties are defined in the Component interface; see Secção 5.2.1,“Component Interface” for further details.

Layout Properties

The size of a component is determined by its width and height, which you can give in the twoedit boxes in the control panel. You can use any unit specifiers for components, as described inSecção 5.3.9, “Sizing Components”. Emptying a size box will make the size "automatic", whichmeans setting the size as undefined. In the generated code, the undefined value will be expressedas "-1px".

Setting width of "100px" and auto (undefined or empty) height would result in the followinggenerated settings for a button:

// myButtonmyButton = new Button();...myButton.setHeight("-1px");myButton.setWidth("100px");...

Figura 7.4, “Layout Properties” shows the control panel area for the size and position.

Figura 7.4. Layout Properties

The generated code for the example would be:

Setting Component Properties262

Visual User Interface Design with Eclipse

Page 265: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// myButtonmyButton = new Button();myButton.setWidth("-1px");myButton.setHeight("-1px");myButton.setImmediate(true);myButton.setCaption("My Button");mainLayout.addComponent(myButton, "top:243.0px;left:152.0px;");

The position is given as a CSS position in the second parameter for addComponent(). Thevalues "-1px" for width and height will make the button to be sized automatically to the minimumsize required by the caption.

When editing the position of a component inside an AbsoluteLayout, the editor will displayvertical and horizontal guides, which you can use to set the position of the component. SeeSecção 7.3.3, “Editing an AbsoluteLayout” for more information about editing absolute layouts.

The ZIndex setting controls the "Z coordinate" of the components, that is, which component willoverlay which when they overlap. Value -1 means automatic, in which case the componentsadded to the layout later will be on top.

7.3.3. Editing an AbsoluteLayout

The visual editor has interactive support for the AbsoluteLayout component that allows positioningcomponents exactly at specified coordinates.You can position the components using guides thatcontrol the position attributes, shown in the control panel on the right. The position values aremeasured in pixels from the corresponding edge; the vertical and horizontal rulers show thedistances from the top and left edge.

Figura 7.5, “Positioning with AbsoluteLayout” shows three components, a Label, a Table, anda Button, inside an AbsoluteLayout.

Figura 7.5. Positioning with AbsoluteLayout

263Editing an AbsoluteLayout

Visual User Interface Design with Eclipse

Page 266: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Position attributes that are empty are automatic and can be either zero (at the edge) or dynamicto make it shrink to fit the size of the component, depending on the component. Guides are shownalso for the automatic position attributes and move automatically; in Figura 7.5, “Positioning withAbsoluteLayout” the right and bottom edges of the Button are automatic.

Moving an automatic guide manually makes the guide and the corresponding the position attributenon-automatic. To make a manually set attribute automatic, empty it in the control panel.Figura 7.6, “Manually positioned Label” shows a Label component with all the four edges setmanually. Notice that if an automatic position is 0, the guide is at the edge of the ruler.

Figura 7.6. Manually positioned Label

7.4. Structure of a Visually Editable Component

A component created by the wizard and later managed by the visual editor has a very specificstructure that allows you to insert your user interface logic in the component while keeping aminimal amount of code off-limits.You need to know what you can edit yourself and what exactlyis managed by the editor. The managed member variables and methods are marked with theAutoGenerated annotation, as you can see later.

A visually editable component consists of:

• Member variables containing sub-component references

• Sub-component builder methods

• The constructor

The structure of a composite component is hierarchical, a nested hierarchy of layout componentscontaining other layout components as well as regular components. The root layout of thecomponent tree, or the composition root of the CustomComponent, is named mainLayout.See Secção 5.24, “Component Composition with CustomComponent” for a detailed descriptionof the structure of custom (composite) components.

Structure of a Visually Editable Component264

Visual User Interface Design with Eclipse

Page 267: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

7.4.1. Sub-Component References

The CustomComponent class will include a reference to each contained component as a membervariable. The most important of these is the mainLayout reference to the composition rootlayout. Such automatically generated member variables are marked with the @AutoGeneratedannotation. They are managed by the editor, so you should not edit them manually, unless youknow what you are doing.

A composite component with an AbsoluteLayout as the composition root, containing a Buttonand a Table would have the references as follows:

public class MyComponent extends CustomComponent {

@AutoGenerated private AbsoluteLayout mainLayout; @AutoGenerated private Button myButton; @AutoGenerated private Table myTable; ...

The names of the member variables are defined in the component properties panel of the visualeditor, in the Component name field, as described in “Basic Properties”. While you can changethe name of any other components, the name of the root layout is always mainLayout. It is fixedbecause the editor does not make changes to the constructor, as noted in Secção 7.4.3, “TheConstructor”.You can, however, change the type of the root layout, which is an AbsoluteLayoutby default.

Certain typically static components, such as the Label label component, will not have a referenceas a member variable. See the description of the builder methods below for details.

7.4.2. Sub-Component Builders

Every managed layout component will have a builder method that creates the layout and all itscontained components. The builder puts references to the created components in theircorresponding member variables, and it also returns a reference to the created layout component.

Below is an example of an initial main layout:

@AutoGeneratedprivate AbsoluteLayout buildMainLayout() { // common part: create layout mainLayout = new AbsoluteLayout();

// top-level component properties setHeight("100.0%"); setWidth("100.0%");

return mainLayout;}

Notice that while the builder methods return a reference to the created component, they alsowrite the reference directly to the member variable. The returned reference might not be usedby the generated code at all (in the constructor or in the builder methods), but you can use it foryour purposes.

265Sub-Component References

Visual User Interface Design with Eclipse

Page 268: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The builder of the main layout is called in the constructor, as explained in Secção 7.4.3, “TheConstructor”.When you have a layout with nested layout components, the builders of each layoutwill call the appropriate builder methods of their contained layouts to create their contents.

7.4.3.The Constructor

When you create a new composite component using the wizard, it will create a constructor forthe component and fill its basic content.

public MyComponent() { buildMainLayout(); setCompositionRoot(mainLayout);

// TODO add user code here }

The most important thing to do in the constructor is to set the composition root of theCustomComponent with the setCompositionRoot() (see Secção 5.24, “ComponentComposition with CustomComponent” for more details on the composition root).The generatedconstructor first builds the root layout of the composite component with buildMainLayout()and then uses the mainLayout reference.

The editor will not change the constructor afterwards, so you can safely change it as you want.The editor does not allow changing the member variable holding a reference to the root layout,so it is always named mainLayout.

The Constructor266

Visual User Interface Design with Eclipse

Page 269: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 8

Themes

8.1. Overview ................................................................................................ 2678.2. Introduction to Cascading Style Sheets ................................................. 2698.3. Syntactically Awesome Stylesheets (Sass) ........................................... 2768.4. Creating and Using Themes .................................................................. 2818.5. Creating a Theme in Eclipse .................................................................. 2858.6. Valo Theme ............................................................................................ 2868.7. Custom Fonts ........................................................................................ 2918.8. Responsive Themes .............................................................................. 291

This chapter provides details about using and creating themes that control the visual look of webapplications. Themes are created using Sass, which is an extension of CSS (Cascading StyleSheets), or with plain CSS. We provide an introduction to CSS, especially concerning the stylingof HTML by element classes.

8.1. Overview

Vaadin separates the appearance of the user interface from its logic using themes. Themes caninclude Sass or CSS style sheets, custom HTML layouts, and any necessary graphics. Themeresources can also be accessed from application code as ThemeResource objects.

Custom themes are placed under the VAADIN/themes/ folder of the web application (underWebContent in Eclipse or src/main/webapp in Maven projects). This location is fixed -- theVAADIN folder contains static resources that are served by the Vaadin servlet. The servletaugments the files stored in the folder by resources found from corresponding VAADIN folderscontained in JARs in the class path. For example, the built-in themes are stored in the vaadin-themes.jar.

267Book of Vaadin

Page 270: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 8.1, “Contents of a Theme” illustrates the contents of a theme.

Figura 8.1. Contents of a Theme

The name of a theme folder defines the name of the theme. The name is used in the @Themeannotation that sets the theme. A theme must contain either a styles.scss for Sass themes,or styles.css stylesheet for plain CSS themes, but other contents have free naming. Werecommend that you have the actual theme content in a SCSS file named after the theme, suchas mytheme.scss, to make the names more unique.

We also suggest a convention for naming the folders as img for images, layouts for customlayouts, and css for additional stylesheets.

Custom themes need to extend a base theme, as described in Secção 8.4, “Creating and UsingThemes”. Copying and modifying an existing theme is also possible, but it is not recommended,as it may need more work to maintain if the modifications are small.

You use a theme by specifying it with the @Theme annotation for the UI class of the applicationas follows:

@Theme("mytheme")public class MyUI extends UI { @Override protected void init(VaadinRequest request) { ... }}

A theme can contain alternate styles for user interface components, which can be changed asneeded.

In addition to style sheets, a theme can contain HTML templates for custom layouts used withCustomLayout. See Secção 6.14, “Custom Layouts” for details.

Overview268

Themes

Page 271: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Resources provided in a theme can also be accessed using the ThemeResource class, asdescribed in Secção 4.4.4, “Recursos de Tema”. This allows displaying theme resources incomponent icons, in the Image component, and other such uses.

8.2. Introduction to Cascading Style Sheets

Cascading Style Sheets or CSS is the basic technique to separate the appearance of a web pagefrom the content represented in HTML. In this section, we give an introduction to CSS and lookhow they are relevant to software development with Vaadin.

8.2.1. CSS Information Sources

As we can only give a short intruction in this book, we encourage you to refer to the rich literatureon CSS and the many resources available in the web. You can find the authoratitativespecifications of CSS standards from the W3C websiteand other literature, references, andtutorials from the Open Directory Project page on CSS, as well as from other sources.

8.2.1. Applying CSS to HTML

Let us consider the following HTML document that contains various markup elements for formattingtext. Vaadin UIs work in essentially similar documents, even though they use somewhat differentelements to draw the user interface.

<html> <head> <title>My Page</title> <link rel="stylesheet" type="text/css" href="mystylesheet.css"/> </head> <body>

<p>This is a paragraph</p><p>This is another paragraph</p>

<table> <tr>

<td>This is a table cell</td><td>This is another table cell</td>

</tr> </table> </body></html>

The HTML elements that will be styled later by matching CSS rules are emphasized above.

The <link> element in the HTML header defines the used CSS stylesheet. The definition isautomatically generated by Vaadin in the HTML page that loads the UI of the application. Astylesheet can also be embedded in the HTML document itself, as is done when optimizing theirloading in Vaadin TouchKit, for example.

8.2.2. Basic CSS Rules

A stylesheet contains a set of rules that can match the HTML elements in the page. Each ruleconsists of one or more selectors, separated with commas, and a declaration block enclosed incurly braces. A declaration block contains a list of property statements. Each property has a labeland a value, separated with a colon. A property statement ends with a semicolon.

269Introduction to Cascading Style Sheets

Themes

Page 272: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Let us look at an example that matches certain elements in the simple HTML document given inthe previous section:

p, td { color: blue;}

td { background: yellow; font-weight: bold;}

The p and td are element type selectors that match with <p> and <td> elements in HTML,respectively.The first rule matches with both elements, while the second matches only with <td>elements. Let us assume that you have saved the above style sheet with the namemystylesheet.css and consider the following HTML file located in the same folder.

Figura 8.2. Simple Styling by Element Type

Style Inheritance in CSS

CSS has inheritance where contained elements inherit the properties of their parent elements.For example, let us change the above example and define it instead as follows:

table { color: blue; background: yellow;}

All elements contained in the <table> element would have the same properties. For example,the text in the contained <td> elements would be in blue color.

HTML Element Types

HTML has a number of element types, each of which accepts a specific set of properties. The<div> elements are generic elements that can be used to create almost any layout and formattingthat can be created with a specific HTML element type.Vaadin uses <div> elements extensivelyto draw the UI, especially in layout components.

Matching elements by their type as shown above is, however, rarely if ever used in style sheetsfor Vaadin applications. We used it above, because it is the normal way in regular HTMLdocuments that use the various HTML elements for formatting text, but it is not applicable inVaadin UIs that consist mostly of <div> elements. Instead, you need to match by element class,as described next.

8.2.3. Matching by Element Class

Matching HTML elements by the class attribute is the most common form of matching in Vaadinstylesheets. It is also possible to match with the identifier of a unique HTML element.

Matching by Element Class270

Themes

Page 273: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The class of an HTML element is defined with the class attribute as follows:

<html> <body>

<p class="normal">This is the first paragraph</p>

<p class="another">This is the second paragraph</p>

<table> <tr>

<td class="normal">This is a table cell</td><td class="another">This is another table cell</td>

</tr> </table> </body></html>

The class attributes of HTML elements can be matched in CSS rules with a selector notationwhere the class name is written after a period following the element name. This gives us fullcontrol of matching elements by their type and class.

p.normal {color: red;}p.another {color: blue;}td.normal {background: pink;}td.another {background: yellow;}

The page would look as shown below:

Figura 8.3. Matching HTML Element Type and Class

We can also match solely by the class by using the universal selector * for the element name,for example *.normal. The universal selector can also be left out altogether so that we use justthe class name following the period, for example .normal.

.normal { color: red;}

.another { blackground: yellow;}

In this case, the rule will match with all elements of the same class regardless of the elementtype. The result is shown in Figura 8.4, “Matching Only HTML Element Class”. This exampleillustrates a technique to make style sheets compatible regardless of the exact HTML elementused in drawing a component.

271Matching by Element Class

Themes

Page 274: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 8.4. Matching Only HTML Element Class

To ensure future compatibility, we recommend that you use only matching based on the classesand do not match for specific HTML element types in CSS rules, because Vaadin may changethe exact HTML implementation how components are drawn in the future. For example, Vaadinearlier used <div> element to draw Button components, but later it was changed to use thespecial-purpose <button> element in HTML. Because of using the v-button style class in theCSS rules for the button, styling it has changed only very little.

8.2.4. Matching by Descendant Relationship

CSS allows matching HTML by their containment relationship. For example, consider the followingHTML fragment:

<body> <p class="mytext">Here is some text inside a paragraph element</p> <table class="mytable"> <tr> <td class="mytext">Here is text inside a table and inside a td element.</td> </tr> </table></body>

Matching by the class name .mytext alone would match both the <p> and <td> elements. Ifwe want to match only the table cell, we could use the following selector:

.mytable .mytext {color: blue;}

To match, a class listed in a rule does not have to be an immediate descendant of the previousclass, but just a descendant. For example, the selector ".v-panel .v-button" would matchall elements with class .v-button somewhere inside an element with class .v-panel.

8.2.5. Importance of Cascading

CSS or Cascading Stylesheets are, as the name implies, about cascading stylesheets, whichmeans applying the stylesheet rules according to their origin, importance, scope, specifity, andorder.

For exact rules for cascading in CSS, see the section Cascading in the CSS specification.

Importance

Declarations in CSS rules can be made override declarations with otherwise higher priority byannotating them as !important. For example, an inline style setting made in the style attributeof an HTML element has a higher specificity than any rule in a CSS stylesheet.

<div class="v-button" style="height: 20px;">...

You can override the higher specificity with the !important annotation as follows:

Matching by Descendant Relationship272

Themes

Page 275: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

.v-button {height: 30px !important;}

Specificity

A rule that specifies an element with selectors more closely overrides ones that specify it lessspecifically. With respect to the element class selectors most commonly used in Vaadin themes,the specificity is determined by the number of class selectors in the selector.

.v-button {}

.v-verticallayout .v-button {}

.v-app .v-verticallayout .v-button {}

In the above example, the last rule would have the highest specificity and would match.

As noted earlier, style declarations given in the style attribute of a HTML element have higherspecificity than declarations in a CSS rule, except if the !important annotation is given.

See the CSS3 selectors module specification for details regarding how the specificity is computed.

Order

CSS rules given later have higher priority than ones given earlier. For example, in the following,the latter rule overrides the former and the color will be black:

.v-button {color: white}

.v-button {color: black}

As specificity has a higher cascading priority than order, you could make the first rule have higherpriority by adding specificity as follows:

.v-app .v-button {color: white}

.v-button {color: black}

The order is important to notice in certain cases, because Vaadin does not guarantee the orderin which CSS stylesheets are loaded in the browser, which can in fact be random and result invery unexpected behavior. This is not relevant for Sass stylesheets, which are compiled to asingle stylesheet. For plain CSS stylesheets, such as add-on or TouchKit stylesheets, the ordercan be relevant.

8.2.6. Style Class Hierarchy of a Vaadin UI

Let us give a real case in a Vaadin UI by considering a simple Vaadin UI with a label and a buttoninside a vertical layout:

// UI has v-ui style class@Theme("mytheme")public class HelloWorld extends UI { @Override protected void init(VaadinRequest request) { // VerticalLayout has v-verticallayout style VerticalLayout content = new VerticalLayout(); setContent(content);

// Label has v-label style content.addComponent(new Label("Hello World!"));

// Button has v-button style content.addComponent(new Button("Push Me!",

273Style Class Hierarchy of a Vaadin UI

Themes

Page 276: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { Notification.show("Pushed!"); } })); }}

The UI will look by default as shown in Figura 8.5, “An Unthemed Vaadin UI”. By using a HTMLinspector such as Firebug, you can view the HTML tree and the element classes and appliedstyles for each element.

Figura 8.5. An Unthemed Vaadin UI

Style Class Hierarchy of a Vaadin UI274

Themes

Page 277: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Now, let us look at the HTML element class structure of the UI, as we can see it in the HTMLinspector:

<body class="v-generated-body v-ff v-ff20 v-ff200 v-gecko v-lin" scroll="auto"> <div id="bookexamplesvaadin7helloworld-447164942" class="v-app mytheme"> <div class="v-ui v-scrollable" tabindex="1" style="height: 100%; width: 100%;"> <div class="v-loading-indicator first" style="position: absolute; display: none;"></div> <div class="v-verticallayout v-layout v-vertical v-widget v-has-width" style="width: 100%;"> <div class="v-slot"> <div class="v-label v-widget v-has-width" style="width: 100%;">Hello World!</div> </div> <div class="v-slot"> <div class="v-button v-widget" tabindex="0" role="button"> <span class="v-button-wrap"> <span class="v-button-caption">Push Me!</span> </span> </div> </div> </div> </div> </div> ...<body>

Now, consider the following theme where we set the colors and margins of various elements.The theme is actually a Sass theme.

@import "../reindeer/reindeer.scss";

@mixin mytheme { @include reindeer;

/* White background for the entire UI */ .v-ui { background: white; }

/* All labels have white text on black background */ .v-label { background: black; color: white; font-size: 24pt; line-height: 24pt; padding: 5px; }

/* All buttons have blue caption and some margin */ .v-button { margin: 10px;

/* A nested selector to increase specificity */

275Style Class Hierarchy of a Vaadin UI

Themes

Page 278: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

.v-button-caption { color: blue; } }}

The look has changed as shown in Figura 8.6, “Themed Vaadin UI”.

Figura 8.6.Themed Vaadin UI

An element can have multiple classes separated with a space. With multiple classes, a CSS rulematches an element if any of the classes match.This feature is used in many Vaadin componentsto allow matching based on the state of the component. For example, when the mouse is overa Link component, over class is added to the component. Most of such styling is a feature ofGoogle Web Toolkit.

8.2.7. Notes on Compatibility

CSS is a standard continuously under development. It was first proposed in 1994.The specificationof CSS is maintained by the CSS Working Group of World Wide Web Consortium (W3C).Versioned with backward-compatible "levels", CSS Level 1 was published in 1996, Level 2 in1998, and the ongoing development of CSS Level 3 started in 1998. CSS3 is divided into anumber of separate modules, each developed and progressing separately, and many of themodules are already Level 4.

While the support for CSS has been universal in all graphical web browsers since at least 1995,the support has been very incomplete at times and there still exists an unfortunate number ofincompatibilities between browsers.While we have tried to take these incompatibilities into accountin the built-in themes in Vaadin, you need to consider them while developing your own themes.Compatibility issues are detailed in various CSS handbooks.

8.3. Syntactically Awesome Stylesheets (Sass)

Vaadin uses Sass for stylesheets. Sass is an extension of CSS3 that adds nested rules, variables,mixins, selector inheritance, and other features to CSS. Sass supports two formats for stylesheet:Vaadin themes are written in SCSS (.scss), which is a superset of CSS3, but Sass also allowsa more concise indented format (.sass).

Notes on Compatibility276

Themes

Page 279: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Sass can be used in two basic ways in Vaadin applications, either by compiling SCSS files toCSS or by doing the compilation on the fly. The latter way is possible if the development modeis enabled for the Vaadin servlet, as described in Secção 4.8.6, “Outros Parâmetros deConfiguração de Servlet”.

8.3.1. Sass Overview

Variables

Sass allows defining variables that can be used in the rules.

$textcolor: blue;

.v-button-caption { color: $textcolor;}

The above rule would be compiled to CSS as:

.v-button-caption { color: blue;}

Also mixins can have variables as parameters, as explained later.

Nesting

Sass supports nested rules, which are compiled into inside-selectors. For example:

.v-app { background: yellow;

.mybutton { font-style: italic;

.v-button-caption { color: blue; } }}

is compiled as:

.v-app { background: yellow;}

.v-app .mybutton { font-style: italic;}

.v-app .mybutton .v-button-caption { color: blue;}

277Sass Overview

Themes

Page 280: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Mixins

Mixins are rules that can be included in other rules. You define a mixin rule by prefixing it withthe @mixin keyword and the name of the mixin. You can then use @include to apply it toanother rule. You can also pass parameters to it, which are handled as local variables in themixin.

For example:

@mixin mymixin { background: yellow;}

@mixin othermixin($param) { margin: $param;}

.v-button-caption { @include mymixin; @include othermixin(10px);}

The above SCSS would translated to the following CSS:

.v-button-caption { background: yellow; margin: 10px;}

You can also have nested rules in a mixin, which makes them especially powerful. Mixing in rulesis used when extending Vaadin themes, as described in Secção 8.4.1, “Sass Themes”.

Vaadin themes are defined as mixins to allow for certain uses, such as different themes fordifferent portlets in a portal.

8.3.2. Sass Basics with Vaadin

We are not going to give in-depth documentation of Sass and refer you to its excellentdocumentation at http://sass-lang.com/. In the following, we give just basic introduction to usingit with Vaadin.

You can create a new Sass-based theme with the Eclipse plugin, as described in Secção 8.5,“Creating a Theme in Eclipse”.

8.3.3. Compiling Sass Themes

Compiling On the Fly

The easiest way to use Sass themes is to let the Vaadin servlet compile them on the run. In thiscase, the SCSS source files are placed in the theme folder. Compilation is done each time thestyles.css is requested from the server.

The on-the-fly compilation takes a bit time, so it is only available when the Vaadin servlet is inthe development mode, as described in Secção 4.8.6, “Outros Parâmetros de Configuração deServlet”. Also, it requires the theme compiler and all its dependencies to be in the class path ofthe servlet. For production, you should compile the theme to CSS, as described next.

Sass Basics with Vaadin278

Themes

Page 281: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Compiling in Eclipse

If using Eclipse and the Vaadin Plugin for Eclipse, its project wizard creates a Sass theme. Itincludes Compile Theme command in the toolbar to compile the project theme to CSS. Anothercommand compiles also the widget set.

Figura 8.7. Compiling Sass Theme

The WebContent/VAADIN/mytheme/styles.scss and any Sass sources included by it arecompiled to styles.css.

Compiling with Maven

To compile the themes with Maven, you need to include the built-in themes as a dependency:

... <dependencies> ... <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-themes</artifactId> <version>${vaadin.version}</version> </dependency> </dependencies> ...

This is automatically included at least in the vaadin-archetype-application archetype forVaadin applications. The actual theme compilation is most conveniently done by the VaadinMaven Plugin with update-theme and compile-theme goals.

... <plugin> <groupId>com.vaadin</groupId> <artifactId>vaadin-maven-plugin</artifactId> ... <executions> <execution> ... <goals> <goal>clean</goal> <goal>resources</goal> <goal>update-theme</goal> <goal>update-widgetset</goal> <goal>compile-theme</goal> <goal>compile</goal> </goals> </execution> </executions>

279Compiling Sass Themes

Themes

Page 282: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Once these are in place, the theme is compiled as part of relevant lifecycle phases, such aspackage.

mvn package

You can also compile just the theme with the compile-theme goal:

mvn vaadin:compile-theme

Compiling in Command-line

Sass style sheets can be compiled to CSS, with the styles.css of a custom theme as thecompilation target. When compiled before deployment, the source files do not need to be in thetheme folder.

java -cp '../../../WEB-INF/lib/*' com.vaadin.sass.SassCompiler styles.scss styles.css

The -cp parameter should point to the class path where the Vaadin JARs are located. In theabove example, they are assumed to be locate in the WEB-INF/lib folder of the web application.If you have loaded the Vaadin libraries using Ivy, as is the case with projects created with theVaadin Plugin for Eclipse, the Vaadin libraries are stored in Ivy's local repository. Its folderhierarchy is somewhat scattered, so we recommend that you retrieve the libraries to a singlefolder. We recommend using an Ant script as is described next.

Compiling with Ant

With Apache Ant, you can easily resolve the dependencies with Ivy and compile the theme withthe Theme Compiler included in Vaadin as follows. This build step can be conveniently includedin a WAR build script.

Start with the following configuration:

<project xmlns:ivy="antlib:org.apache.ivy.ant" name="My Project" basedir="../" default="package-war">

<target name="configure"> <!-- Where project source files are located --> <property name="src-location" value="src" />

... other project build definitions ...

<!-- Name of the theme --> <property name="theme" value="book-examples"/>

<!-- Compilation result directory --> <property name="result" value="build/result"/> </target>

<!-- Initialize build --> <target name="init" depends="configure"> <!-- Construct and check classpath --> <path id="compile.classpath"> <!-- Source code to be compiled --> <pathelement path="${src-location}" />

<!-- Vaadin libraries and dependencies -->

Compiling Sass Themes280

Themes

Page 283: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<fileset dir="${result}/lib"> <include name="*.jar"/> </fileset> </path>

<mkdir dir="${result}"/> </target>

You should first resolve all Vaadin libraries to a single directory, which you can use for deployment,but also for theme compilation.

<target name="resolve" depends="init"> <ivy:retrieve pattern="${result}/lib/[module]-[type]-[artifact]-[revision].[ext]"/> </target>

Then, you can compile the theme as follows:

<!-- Compile theme --> <target name="compile-theme" depends="init, resolve"> <delete dir="${result}/VAADIN/themes/${theme}"/> <mkdir dir="${result}/VAADIN/themes/${theme}"/>

<java classname="com.vaadin.sass.SassCompiler" fork="true"> <classpath> <path refid="compile.classpath"/> </classpath> <arg value="WebContent/VAADIN/themes/${theme}/styles.scss"/> <arg value="${result}/VAADIN/themes/${theme}/styles.css"/> </java>

<!-- Copy theme resources --> <copy todir="${result}/VAADIN/themes/${theme}"> <fileset dir="WebContent/VAADIN/themes/${theme}"> <exclude name="**/*.scss"/> </fileset> </copy> </target></project>

8.4. Creating and Using Themes

Custom themes are placed in the VAADIN/themes folder of the web application, in an Eclipseproject under the WebContent folder or src/main/webapp in Maven projects, as was illustratedin Figura 8.1, “Contents of a Theme”. This location is fixed. You need to have a theme folder foreach theme you use in your application, although applications rarely need more than a singletheme.

8.4.1. Sass Themes

You can use Sass themes in Vaadin in two ways, either by compiling them to CSS by yourselfor by letting the Vaadin servlet compile them for you on-the-fly when the theme CSS is requestedby the browser, as described in Secção 8.3.3, “Compiling Sass Themes”.

281Creating and Using Themes

Themes

Page 284: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

To define a Sass theme with the name mytheme, you must place a file with name styles.scssin the theme folder VAADIN/themes/mytheme. If no styles.css exists in the folder, the Sassfile is compiled on-the-fly when the theme is requested by a browser.

We recommend that you organize the theme in at least two SCSS files so that you import theactual theme from a Sass file that is named more uniquely than the styles.scss, to make itdistinquishable in the editor. This organization is how the Vaadin Plugin for Eclipse creates anew theme.

If you use Vaadin add-ons that contain themes, Vaadin Plugin for Eclipse and Maven automaticallyadd them to the addons.scss file.

Theme SCSS

We recommend that the rules in a theme should be prefixed with a selector for the theme name.You can do the prefixing in Sass by enclosing the rules in a nested rule with a selector for thetheme name.

Themes are defined as Sass mixins, so after you import the mixin definitions, you can @includethem in the theme rule as follows:

@import "addons.scss";@import "mytheme.scss";

.mytheme { @include addons; @include mytheme;}

However, this is mainly necessary if you use the UI in portlets, each of which can have its owntheme, or in the special circumstance that the theme has rules that use empty parent selector &to refer to the theme name.

Otherwise, you can safely leave the nested theme selector out as follows:

@import "addons.scss";@import "mytheme.scss";

@include addons;@include mytheme;

The actual theme should be defined as follows, as a mixin that includes the base theme.

@import "../reindeer/reindeer.scss";

@mixin mytheme { @include reindeer;

/* An actual theme rule */ .v-button { color: blue;

Sass Themes282

Themes

Page 285: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

}}

8.4.2. Plain Old CSS Themes

In addition to Sass themes, you can create plain old CSS themes. CSS theme are more restrictedthan Sass styles - an application can only have one CSS theme while you can have multipleSass themes.

A CSS theme is defined in a styles.css file in the VAADIN/themes/mytheme folder. Youneed to import the legacy-styles.css of the built-in theme as follows:

@import "../reindeer/legacy-styles.css";

.v-app { background: yellow;}

8.4.3. Styling Standard Components

Each user interface component in Vaadin has a CSS style class that you can use to control theappearance of the component. Many components have additional sub-elements that also allowstyling. You can add context-specific stylenames with addStyleName(). Notice thatgetStyleName() returns only the custom stylenames, not the built-in stylenames for thecomponent.

Please see the section on each component for a description of its styles. Most of the stylenamesare determined in the client-side widget of each component.The easiest way to find out the stylesof the elements is to use a HTML inspector such as FireBug.

Some client-side components or component styles can be shared by different server-sidecomponents. For example, v-textfield style is used for all text input boxes in components,in addition to TextField.

8.4.4. Built-in Themes

Vaadin currently includes the following built-in themes:

• valo, the primary theme in Vaadin 7.3 (upcoming)

• reindeer, the primary theme in Vaadin 6 and 7

• chameleon, an easily customizable theme

• runo, the default theme in IT Mill Toolkit 5

• liferay, for Liferay portlets

In addition, there is the base theme, which should not be used directly, but is extended by theother built-in themes, except valo.

The built-in themes are provided in the respective VAADIN/themes/<theme>/styles.scssstylesheets in the vaadin-themes JAR. Also the precompiled CSS files are included, in caseyou want to use the themes directly.

283Plain Old CSS Themes

Themes

Page 286: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Various constants related to the built-in themes are defined in the theme classes incom.vaadin.ui.themes package. These are mostly special style names for specific components.

@Theme("runo")public class MyUI extends UI { @Override protected void init(VaadinRequest request) { ... Panel panel = new Panel("Regular Panel in the Runo Theme"); panel.addComponent(new Button("Regular Runo Button"));

// A button with the "small" style Button smallButton = new Button("Small Runo Button"); smallButton.addStyleName(Runo.BUTTON_SMALL);

Panel lightPanel = new Panel("Light Panel"); lightPanel.addStyleName(Runo.PANEL_LIGHT); lightPanel.addComponent( new Label("With addStyleName(\"light\")")); ...

The example with the Runo theme is shown in Figura 8.8, “Runo Theme”.

Figura 8.8. Runo Theme

The built-in themes come with a custom icon font, FontAwesome, which is used for icons in thetheme, and which you can use as font icons, as described in Secção 11.17, “Font Icons”.

Serving Built-In Themes Statically

The built-in themes included in the Vaadin library JAR are served dynamically fromthe JAR by the servlet. Serving themes and widget sets statically by the web serveris more efficient. To do so, you need to extract the VAADIN/ directories from theJAR to the web content directory (WebContent in Eclipse or src/main/webappin Maven projects).

$ cd WebContent

$ unzip path-to/vaadin-server-7.x.x.jar 'VAADIN/*'

$ unzip path-to/vaadin-themes-7.x.x.jar 'VAADIN/*'

$ unzip path-to/vaadin-client-compiled-7.x.x.jar 'VAADIN/*'

Built-in Themes284

Themes

Page 287: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

You can also serve static content from a front-end caching server, which reducesthe load of the application server. In portals, you install the themes globally in theportal as described in Secção 12.5.2, “Installing Vaadin”.

Just make sure to update the static content when you upgrade to a newer versionof Vaadin.

Creation of a default theme for custom GWT widgets is described in Secção 16.8, “Styling aWidget”.

8.4.5. Add-on Themes

You can find more themes as add-ons from the Vaadin Directory. In addition, many componentadd-ons contain a theme for the components they provide.

The add-on themes need to be included in the project theme. Vaadin Plugin for Eclipse andMaven automatically include them in the addons.scss file in the project theme folder. It shouldbe included by the project theme.

8.5. Creating a Theme in Eclipse

The Eclipse plugin automatically creates a theme stub for new Vaadin projects. It also includesa wizard for creating new custom themes. Do the following steps to create a new theme.

1. Select File   New   Other... in the main menu or right-click the Project Explorer andselect New   Other.... A window will open.

2. In the Select a wizard step, select the Vaadin   Vaadin Theme wizard.

Click Next to proceed to the next step.

3. In the Create a new Vaadin theme step, you have the following settings:

Project (mandatory)The project in which the theme should be created.

Theme name (mandatory)The theme name is used as the name of the theme folder and in a CSS tag (prefixedwith "v-theme-"), so it must be a proper identifier. Only latin alphanumerics,underscore, and minus sign are allowed.

285Add-on Themes

Themes

Page 288: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Modify application classes to use theme (optional)The setting allows the wizard to write a code statement that enables the theme inthe constructor of the selected application (UI) class(es). If you need to control thetheme with dynamic logic, you can leave the setting unchecked or change thegenerated line later.

Click Finish to create the theme.

The wizard creates the theme folder under the WebContent/VAADIN/themes folder and theactual style sheet as mytheme.scss and styles.scss files, as illustrated in Figura 8.9, “NewlyCreated Theme”.

Figura 8.9. Newly Created Theme

The created theme extends a built-in base theme with an @import statement. See the explanationof theme inheritance in Secção 8.4, “Creating and Using Themes”. Notice that the reindeertheme is not located in the widgetsets folder, but in the Vaadin JAR. See Secção 8.4.4, “Built-in Themes” for information for serving the built-in themes.

If you selected a UI class or classes in the Modify application classes to use theme in thetheme wizard, the wizard will add the @Theme annotation to the UI class.

If you later rename the theme in Eclipse, notice that changing the name of the folder will notautomatically change the @Theme annotation. You need to change such references to themenames in the calls manually.

8.6. Valo Theme

Valo is the new built-in theme in Vaadin 7.3. It is included in prerelease versions. At least7.3.0.alpha1 still requires using the standard Sass compiler (version 3.2) on command-line,instead of the Vaadin Sass compiler.

Valo is the word for light in Finnish. For mere geographical reasons, Finland is obsessed withlight, with long winters without much sunlight but plenty of whiteness and long summer daysbathed in light. Light is one of the cornerstones of visual arts, perhaps the most important one.A visual design begins from the use of light in an array of shades together with a color theory, to

Valo Theme286

Themes

Page 289: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

create a unique color scheme that illustrates a unique idea. Valo incorporates the use of light inits theoretical logic. It creates lines, borders, highlights, and shadows adaptively according to abackground color, always with contrasts pleasant to human visual perception. A color theory isused to determine auxiliary colors that blend gently with the background. The static art iscomplemented with responsive animations.

8.6.1. Basic Use

Valo is used just like other themes. Its optional parameters must be given before the @importstatement.

// Modify the base color of the theme$v-app-background-color: hsl(200, 50%, 50%);

// Import valo after setting the parameters@import "../valo/valo";

.mythemename { @include valo;

// Your theme's rules go here}

If you need to override mixins or function definitions in the valo theme, you must do that after theimport statement, but before including the valo mixin.

8.6.2. Common Settings

In the following, we describe the optional parameters that control the visual appearance of theValo theme. In addition to the ones given here, component styles have their own parameters,listed in the sections describing the components in the other chapters.

General Settings

$v-app-loading-text (default: "")A static text that is shown while the client-side engine is being loaded and started.

$v-line-height (default: 1.55)Base line height for all widgets.

$v-app-background-color (default: hsl(210, 0%, 98%))The background color in any way allowed in CSS: hexadesimal color code, RGB/Avalue, HSL/A value, or a color name. If the color is dark (has low luminance), a lightforeground (text) color that gives high contrast with the background is automaticallyused.

Font Settings

$v-font-size (default: 16px)Base font size. It should be specified in pixels.

$v-font-weight (default: 300)Font weight for normal fonts. It should be defined with a numeric value instead ofsymbolic.

287Basic Use

Themes

Page 290: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

$v-font-color (default: computed)Foreground text color. The default is computed from the background color so that itgives a high contrast with the background.

$v-font-family (default: "Open Sans", sans-serif)Font family and fallback fonts. The default font Open Sans is a web font included inthe Valo theme. Other used Valo fonts must be specified in the list to enable them.See Secção 8.6.3, “Valo Fonts”.

$v-caption-font-size (default: round($v-font-size * 0.9))Font size for component captions. The value should be a pixel value.

$v-caption-font-weight (default: max(400, $v-font-weight))Font weight for captions. It should be defined with a numeric value instead of symbolic.

Layout Settings

$v-unit-size (default: round(2.3 * $v-font-size))Unit size for various measures. The value must be specified in pixels, with a suitablerange of 18-50.

$v-layout-margin-top, $v-layout-margin-right, $v-layout-margin-bottom,$v-layout-margin-left (default: $v-unit-size)

Layout margin sizes when the margin is enabled with setMargin(), as described inSecção 6.13.5, “Layout Margins”.

$v-layout-spacing-vertical and $v-layout-spacing-horizontal (default:round($v-unit-size/3))

Amount of vertical or horizontal space when spacing is enabled for a layout withsetSpacing(), as described in Secção 6.13.4, “Layout Cell Spacing”.

Component Features

The following settings apply to various graphical features of some components.

$v-border-width (default: 1px)Border thickness for components that have one. The measure must be specified inpixels.

$v-border-radius (default: 4px)Corner radius for components that have a border. The measure must be specified inpixels.

$v-gradient-style (default: v-linear)Name of the color gradient style for components that have a gradient.

$v-gradient-depth (default: 8%)Gradient depth.

$v-bevel-style (default:inset 0 1px 0 v-hilite, inset 0 -1px 0 v-shade)CSS shadow style to create bevels in some components.The value is a list of a highlightand shade insets.

Common Settings288

Themes

Page 291: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

$v-bevel-depth (default: 25%)The "depth" of a bevel shadow in a component. The actual amount of highlight andshade is computed from the depth.

$v-focus-style (default: 0 0 0 2px v-focus-color)Shadow specification for the field focus indicator: horizontal shadow position in pixels,vertical shadow position in pixels, blur distance in pixels, spread distance in pixels,and the color.The value v-focus-color is substituted with the value of $v-focus-color.

$v-focus-color (default: null)Color for the field focus indicator.null value defaults to a high-contrast color computedfrom the background color.

$v-animations-enabled (default: true)Specifies whether various CSS animations are used.

$v-hover-styles-enabled (default: true)Specifies whether various :hover styles are used.

$v-disabled-opacity (default: 0.7)Opacity of disabled components, which are described in Secção 5.3.3, “Enabled”.

$v-selection-color (default: null)Color of selection indicator in selection and various other components.The null valuedefaults to a high-contrast color computed from the background and foreground colors.

$v-default-field-width (default: $v-unit-size * 5)Default width of certain field components, unless overridden with setWidth().

$v-error-indicator-color (default: #ed473b)Color of the component error indicator.

Theme Compilation and Optimization

$v-relative-paths (default: false)This flags specifies whether relative URL paths are relative to the currently parsedSCSS file or to the compilation root file, so that paths are correct for different resources.Vaadin theme compiler parses URL paths differently from the regular Sass compiler(Vaadin modifies relative URL paths). Use false for Ruby compiler and true forVaadin compiler.

$v-included-components (default: component list)Theme optimization parameter to specify the included component themes, as describedin Secção 8.6.5, “Theme Optimization”.

$v-valo-include-common-stylenames (default: true)Theme optimization parameter that specifies whether the common componentstylenames, described in Secção 8.6.4, “Component Styles”, should be included inthe theme.

8.6.3. Valo Fonts

Valo includes the following custom fonts:

289Valo Fonts

Themes

Page 292: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

• Open Sans

• Source Sans Pro

• Roboto

• Lato

• Lora

The used fonts must be specified with the $v-font-family parameter for Valo, in a fallbackorder. A font family is used in decreasing order of preference, in case a font with higher preferenceis not available in the browser.You can specify any font families and generic families that browsersmay support. In addition to the primary font family, you can use also others in your application.To enable using the fonts included in Valo, you need to list them in the variable.

$v-font-family: 'Open Sans', sans-serif, 'Source Sans Pro';

Above, we specify Open Sans as the preferred primary font, with any sans-serif font that thebrowser supports as a fallback. In addition, we include the Source Sans Pro as an auxiliary fontthat we can use in custom rules as follows:

.v-label pre { font-family: 'Source Sans Pro', monospace;}

This would specify using the font in any Label component with the PREFORMATTED content mode.

8.6.4. Component Styles

Many components have component-specific styles, such as "small", "large", "light", etc.You can specify the component styles with addStyleName(). The styles are documented inthe component sections elsewhere in the book.

Component styles are optional, but enabled by default.They can be disabled with the $v-valo-include-common-stylenames parameter, as described in Secção 8.6.2, “Common Settings”.

The following variables control some common component styles:

$v-scaling-factor--small (default: 0.8)A scaling multiplier for "small" component styles.

$v-scaling-factor--large (default: 1.2)A scaling multiplier for "large" component styles.

8.6.5.Theme Optimization

Valo theme allows optimizing the size of the compiled theme CSS by including the rules for onlythe components actually used in the application.The included component styles can be specifiedin the $v-included-components variable, which by default includes all components. Thevariable should include a comma-separated list of component names in lower-case letters.

For example, if your UI contains just VerticalLayout, TextField, and Button components, youcould define the variable as follows:

$v-included-components: verticallayout,

Component Styles290

Themes

Page 293: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

textfield, button;

8.7. Custom Fonts

In addition to using the built-in fonts of the browser and the web fonts included in the Vaadinthemes, you can use custom web fonts.

8.7.1. Loading Fonts

You can load web fonts with the font mixin as follows:

@include font(MyFontFamily, '../../mytheme/fonts/myfontfamily');

The statement must be given in the styles.scss file outside the .mytheme {} block.

The first parameter is the name of the font family, which is used to identify the font. If the fontfamily name contains spaces, you need to use single or double quotes around the name.

The second parameter is the base name of the font files without an extension, including a relativepath. Notice that the path is relative to the base theme, where the mixin is defined, not the usedtheme. We recommend placing custom font files under a fonts folder in a theme.

Not all browsers support any single font file format, so the base name is appended with .ttf,.eot, .woff, or .svg suffix for the font file suitable for a user's browser.

8.7.2. Using Custom Fonts

After loaded, you can use a custom font, or actually font family, by its name in CSS and otherwise.

.mystyle { font-family: MyFontFamily;}

Again, if the font family name contains spaces, you need to use single or double quotes aroundthe name.

8.8. Responsive Themes

The Responsive component extension enables size range conditions in CSS selectors, allowingconditional CSS rules that respond to size changes in the browser window on the client-side.See the Vaadin Blog article on Responsive design for some additional information.

You can use the Responsive extension to extend either a component, typically a layout, or theentire UI.You specify the extended component in the constructor.

// Have some component with an appropriate style nameLabel c = new Label("Here be text");c.addStyleName("myresponsive");content.addComponent(c);

// Enable Responsive CSS selectors for the componentnew Responsive(c);

You can now use width-range and height-range conditions in CSS selectors as follows:

291Custom Fonts

Themes

Page 294: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

/* Basic settings for all sizes */.myresponsive { padding: 5px; line-height: 36pt;}

/* Small size */.myresponsive[width-range~="0-300px"] { background: orange; font-size: 16pt;}

/* Medium size */.myresponsive[width-range~="301px-600px"] { background: azure; font-size: 24pt;}

/* Anything bigger */.myresponsive[width-range~="601px-"] { background: palegreen; font-size: 36pt;}

You can have overlapping size ranges, in which case all the selectors matching the current sizeare enabled.

8.8.1. Flexible Wrapping

You can use the CssLayout to have automatic wrap-around when the components in the layoutwould go off right side of the layout. Components that wrap must, however, have either undefinedor fixed width, and thereby can not utilize the full area of the screen. With the Responsiveextension, you can have more flexible wrap-around that gives the component tiles maximumwidth.

In the following, we have a text and image box, which are laid out horizontally with 50-50 sizingif the screen is wide enough, but wrap to a vertical layout if the screen is narrow.

CssLayout layout = new CssLayout();layout.setWidth("100%");layout.addStyleName("flexwrap");content.addComponent(layout);

// Enable Responsive CSS selectors for the layoutnew Responsive(layout);

Label title = new Label("Space is big, really big");title.addStyleName("title");layout.addComponent(title);

Label description = new Label("This is a " + "long description of the image shown " + "on the right or below, depending on the " + "screen width. The text here could continue long.");description.addStyleName("itembox");description.setSizeUndefined();layout.addComponent(description);

Flexible Wrapping292

Themes

Page 295: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Image image = new Image(null, new ThemeResource("img/planets/Earth.jpg"));image.addStyleName("itembox");layout.addComponent(image);

The SCSS could be as follows:

/* Various general settings */.flexwrap { background: black; color: white;

.title { font-weight: bold; font-size: 20px; line-height: 30px; padding: 5px; }

.itembox { white-space: normal; vertical-align: top; }

.itembox.v-label {padding: 5px}}

.flexwrap[width-range~="0-499px"] { .itembox {width: 100%}}

.flexwrap[width-range~="500px-"] { .itembox {width: 50%}}

The layout in the wide mode is shown in Figura 8.10, “Flexible Wrapping”.

293Flexible Wrapping

Themes

Page 296: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 8.10. Flexible Wrapping

You could also play with the display: block vs display: inline-block properties.

Notice that, while the Responsive extension makes it possible to do various CSS trickery withcomponent sizes, the normal rules for component and layout sizes apply, as described inSecção 6.13.1, “Layout Size” and elsewhere, and you should always check the size behaviourof the components. In the above example, we set the label to have undefined width, which disablesword wrap, so we had to re-enable it.

8.8.2.Toggling the Display Property

The display property allows especially powerful ways to offer radically different UIs for differentscreen sizes by enabling and disabling UI elements as needed. For example, you could disablesome parts of the UI when the space gets too small, but bring forth navigation buttons that, whenclicked, add component styles to switch to the hidden parts.

In the following, we simply show alternative components based on screen width:

CssLayout layout = new CssLayout();layout.setWidth("100%");layout.addStyleName("toggledisplay");content.addComponent(layout);

// Enable Responsive CSS selectors for the layoutnew Responsive(layout);

Label enoughspace = new Label("This space is big, mindbogglingly big");enoughspace.addStyleName("enoughspace");layout.addComponent(enoughspace);

Label notenoughspace = new Label("Quite small space");notenoughspace.addStyleName("notenoughspace");layout.addComponent(notenoughspace);

Toggling the Display Property294

Themes

Page 297: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The SCSS could be as follows:

/* Common settings */.toggledisplay { .enoughspace, .notenoughspace { color: white; padding: 5px; }

.notenoughspace { /* Really small */ background: red; font-weight: normal; font-size: 10px; line-height: 15px; }

.enoughspace { /* Really big */ background: darkgreen; font-weight: bold; font-size: 20px; line-height: 30px; }}

/* Quite little space */.toggledisplay[width-range~="0-499px"] { .enoughspace {display: none}}

/* Plenty of space */.toggledisplay[width-range~="500px-"] { .notenoughspace {display: none}}

8.8.3. Responsive Demos

You can find a simple responsive demo at demo.vaadin.com/responsive. It demonstrates theflexible wrapping technique described in “Flexible Wrapping”.

The Book Examples demo provides the examples given in this chapter, as well as some others.

The Parking demo for TouchKit, mentioned in Capítulo 20, Mobile Applications with TouchKit,uses a responsive theme to adapt to mobile devices with different screen sizes and when thescreen orientation changes.

295Responsive Demos

Themes

Page 298: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

296

Page 299: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 9

BindingComponents to

Data

9.1. Overview ................................................................................................ 2979.2. Properties .............................................................................................. 2999.3. Holding properties in Items .................................................................... 3059.4. Creating Forms by Binding Fields to Items ............................................ 3089.5. Collecting Items in Containers ............................................................... 313

This chapter describes the Vaadin Data Model and shows how you can use it to bind componentsdirectly to data sources, such as database queries.

9.1. Overview

The Vaadin Data Model is one of the core concepts of the library.To allow the view (user interfacecomponents) to access the data model of an application directly, we have introduced a standarddata interface.

The model allows binding user interface components directly to the data that they display andpossibly allow to edit. There are three nested levels of hierarchy in the data model: property,

297Book of Vaadin

Page 300: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

item, and container. Using a spreadsheet application as an analogy, these would correspond toa cell, a row, and a table, respectively.

Figura 9.1. Vaadin Data Model

The Data Model is realized as a set of interfaces in the com.vaadin.data package. The packagecontains the Property, Item, and Container interfaces, along with a number of more specializedinterfaces and classes.

Notice that the Data Model does not define data representation, but only interfaces. This leavesthe representation fully to the implementation of the containers.The representation can be almostanything, such as a plain old Java object (POJO) structure, a filesystem, or a database query.

The Data Model is used heavily in the core user interface components of Vaadin, especially thefield components, that is, components that implement the Field interface or more typically extendAbstractField, which defines many common features. A key feature of all the built-in fieldcomponents is that they can either maintain their data by themselves or be bound to an externaldata source. The value of a field is always available through the Property interface. As morethan one component can be bound to the same data source, it is easy to implement variousviewer-editor patterns.

The relationships of the various interfaces are shown in Figura 9.2, “Interface Relationships inVaadin Data Model”; the value change event and listener interfaces are shown only for theProperty interface, while the notifier interfaces are omitted altogether.

Overview298

Binding Components to Data

Page 301: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 9.2. Interface Relationships in Vaadin Data Model

The Data Model has many important and useful features, such as support for change notification.Especially containers have many helper interfaces, including ones that allow indexing, ordering,sorting, and filtering the data. Also Field components provide a number of features involving thedata model, such as buffering, validation, and lazy loading.

Vaadin provides a number of built-in implementations of the data model interfaces. The built-inimplementations are used as the default data models in many field components.

In addition to the built-in implementations, many data model implementations, such as containers,are available as add-ons, either from the Vaadin Directory or from independent sources. Bothcommercial and free implementations exist. The JPAContainer, described in Capítulo 19, VaadinJPAContainer, is the most often used conmmercial container add-on. The installation of add-onsis described in Capítulo 17, Using Vaadin Add-ons. Notice that unlike with most regular add-oncomponents, you do not need to compile a widget set for add-ons that include just data modelimplementations.

9.2. Properties

The Property interface is the base of the Vaadin Data Model. It provides a standardized APIfor a single data value object that can be read (get) and written (set). A property is always typed,but can optionally support data type conversions. The type of a property can be any Java class.Optionally, properties can provide value change events for following their changes.

You can set the value of a property with setValue() and read with getValue().

In the following, we set and read the property value from a TextField component, whichimplements the Property interface to allow accessing the field value.

final TextField tf = new TextField("Name");

299Properties

Binding Components to Data

Page 302: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Set the valuetf.setValue("The text field value");

// When the field value is edited by the usertf.addValueChangeListener( new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { // Do something with the new value layout.addComponent(new Label(tf.getValue())); }});

Changes in the property value usually fire a ValueChangeEvent, which can be handled with aValueChangeListener.The event object provides reference to the property with getProperty().Note that its getValue() method returns the value with Object type, so you need to cast it tothe proper type.

Properties are in themselves unnamed.They are collected in items, which associate the propertieswith names: the Property Identifiers or PIDs. Items can be further contained in containers andare identified with Item Identifiers or IIDs. In the spreadsheet analogy, Property Identifiers wouldcorrespond to column names and Item Identifiers to row names. The identifiers can be arbitraryobjects, but must implement the equals(Object) and hashCode() methods so that they canbe used in any standard Java Collection.

The Property interface can be utilized either by implementing the interface or by using some ofthe built-in property implementations. Vaadin includes a Property interface implementation forarbitrary function pairs and bean properties, with the MethodProperty class, and for simpleobject properties, with the ObjectProperty class, as described later.

In addition to the simple components, selection components provide their current selection asthe property value. In single selection mode, the property is a single item identifier, while inmultiple selection mode it is a set of item identifiers. See the documentation of the selectioncomponents for further details.

Components that can be bound to a property have an internal default data source object, typicallya ObjectProperty, which is described later. As all such components are viewers or editors, alsodescribed later, so you can rebind a component to any data source withsetPropertyDataSource().

9.2.1. Property Viewers and Editors

The most important function of the Property as well as of the other data model interfaces is toconnect classes implementing the interface directly to editor and viewer classes. This meansconnecting a data source (model) to a user interface component (views) to allow editing or viewingthe data model.

A property can be bound to a component implementing the Viewer interface withsetPropertyDataSource().

// Have a data modelObjectProperty property = new ObjectProperty("Hello", String.class);

// Have a component that implements ViewerLabel viewer = new Label();

Property Viewers and Editors300

Binding Components to Data

Page 303: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Bind it to the dataviewer.setPropertyDataSource(property);

You can use the same method in the Editor interface to bind a component that allows editing aparticular property type to a property.

// Have a data modelObjectProperty property = new ObjectProperty("Hello", String.class);

// Have a component that implements ViewerTextField editor = new TextField("Edit Greeting");

// Bind it to the dataeditor.setPropertyDataSource(property);

As all field components implement the Property interface, you can bind any componentimplementing the Viewer interface to any field, assuming that the viewer is able the view theobject type of the field. Continuing from the above example, we can bind a Label to the TextFieldvalue:

Label viewer = new Label();viewer.setPropertyDataSource(editor);

// The value shown in the viewer is updated immediately// after editing the value in the editor (once it// loses the focus)editor.setImmediate(true);

If a field has validators, as described in Secção 5.4.5, “Field Validation”, the validators are executedbefore writing the value to the property data source, or by calling the validate() or commit()for the field.

9.2.2. ObjectProperty Implementation

The ObjectProperty class is a simple implementation of the Property interface that allows storingan arbitrary Java object.

// Have a component that implements Viewer interfacefinal TextField tf = new TextField("Name");

// Have a data model with some dataString myObject = "Hello";

// Wrap it in an ObjectPropertyObjectProperty property = new ObjectProperty(myObject, String.class);

// Bind the property to the componenttf.setPropertyDataSource(property);

9.2.3. Converting Between Property Type and Representation

Fields allow editing a certain type, such as a String or Date. The bound property, on the otherhand, could have some entirely different type. Conversion between a representation edited bythe field and the model defined in the property is handler with a converter that implements theConverter interface.

301ObjectProperty Implementation

Binding Components to Data

Page 304: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Most common type conversions, such as between string and integer, are handled by the defaultconverters. They are created in a converter factory global in the application.

Basic Use of Converters

The setConverter(Converter) method sets the converter for a field. The method is definedin AbstractField.

// Have an integer propertyfinal ObjectProperty<Integer> property = new ObjectProperty<Integer>(42);

// Create a TextField, which edits Stringsfinal TextField tf = new TextField("Name");

// Use a converter between String and Integertf.setConverter(new StringToIntegerConverter());

// And bind the fieldtf.setPropertyDataSource(property);

The built-in converters are the following:

Tabela 9.1. Built-in Converters

ModelRepresentationConverter

IntegerStringStringToIntegerConverter

DoubleStringStringToDoubleConverter

NumberStringStringToNumberConverter

BooleanStringStringToBooleanConverter

DateStringStringToDateConverter

LongDateDateToLongConverter

In addition, there is a ReverseConverter that takes a converter as a parameter and reversesthe conversion direction.

If a converter already exists for a type, the setConverter(Class) retrieves the converter forthe given type from the converter factory, and then sets it for the field. This method is usedimplicitly when binding field to a property data source.

Implementing a Converter

A conversion always occurs between a representation type, edited by the field component, anda model type, that is, the type of the property data source. Converters implement the Converterinterface defined in the com.vaadin.data.util.converter package.

For example, let us assume that we have a simple Complex type for storing complex values.

public class ComplexConverter implements Converter<String, Complex> { @Override public Complex convertToModel(String value, Locale locale) throws ConversionException { String parts[] =

Converting Between Property Type and Representation302

Binding Components to Data

Page 305: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

value.replaceAll("[\\(\\)]", "").split(","); if (parts.length != 2) throw new ConversionException( "Unable to parse String to Complex"); return new Complex(Double.parseDouble(parts[0]), Double.parseDouble(parts[1])); }

@Override public String convertToPresentation(Complex value, Locale locale) throws ConversionException { return "("+value.getReal()+","+value.getImag()+")"; }

@Override public Class<Complex> getModelType() { return Complex.class; }

@Override public Class<String> getPresentationType() { return String.class; }}

The conversion methods get the locale for the conversion as a parameter.

Converter Factory

If a field does not directly allow editing a property type, a default converter is attempted to createusing an application-global converter factory. If you define your own converters that you wish toinclude in the converter factory, you need to implement one yourself. While you could implementthe ConverterFactory interface, it is usually easier to just extend DefaultConverterFactory.

class MyConverterFactory extends DefaultConverterFactory { @Override public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType) { // Handle one particular type conversion if (String.class == presentationType && Complex.class == modelType) return (Converter<PRESENTATION, MODEL>) new ComplexConverter();

// Default to the supertype return super.createConverter(presentationType, modelType); }}

// Use the factory globally in the applicationApplication.getCurrentApplication().setConverterFactory( new MyConverterFactory());

303Converting Between Property Type and Representation

Binding Components to Data

Page 306: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

9.2.4. Implementing the Property Interface

Implementation of the Property interface requires defining setters and getters for the value andthe read-only mode. Only a getter is needed for the property type, as the type is often fixed inproperty implementations.

The following example shows a simple implementation of the Property interface:

class MyProperty implements Property { Integer data = 0; boolean readOnly = false;

// Return the data type of the model public Class<?> getType() { return Integer.class; }

public Object getValue() { return data; }

// Override the default implementation in Object @Override public String toString() { return Integer.toHexString(data); }

public boolean isReadOnly() { return readOnly; }

public void setReadOnly(boolean newStatus) { readOnly = newStatus; }

public void setValue(Object newValue) throws ReadOnlyException, ConversionException { if (readOnly) throw new ReadOnlyException();

// Already the same type as the internal representation if (newValue instanceof Integer) data = (Integer) newValue;

// Conversion from a string is required else if (newValue instanceof String) try { data = Integer.parseInt((String) newValue, 16); } catch (NumberFormatException e) { throw new ConversionException(); } else // Don't know how to convert any other types throw new ConversionException();

// Reverse decode the hexadecimal value }}

Implementing the Property Interface304

Binding Components to Data

Page 307: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Instantiate the property and set its dataMyProperty property = new MyProperty();property.setValue(42);

// Bind it to a componentfinal TextField tf = new TextField("Name", property);

The components get the displayed value by the toString() method, so it is necessary tooverride it. To allow editing the value, value returned in the toString() must be in a formatthat is accepted by the setValue() method, unless the property is read-only.The toString()can perform any type conversion necessary to make the internal type a string, and thesetValue() must be able to make a reverse conversion.

The implementation example does not notify about changes in the property value or in the read-only mode. You should normally also implement at least the Property.ValueChangeNotifierand Property.ReadOnlyStatusChangeNotifier. See the ObjectProperty class for an exampleof the implementation.

9.3. Holding properties in Items

The Item interface provides access to a set of named properties. Each property is identified bya property identifier (PID) and a reference to such a property can be queried from an Item withgetItemProperty() using the identifier.

Examples on the use of items include rows in a Table, with the properties corresponding to tablecolumns, nodes in a Tree, and the the data bound to a Form, with item's properties bound toindividual form fields.

Items are generally equivalent to objects in the object-oriented model, but with the exception thatthey are configurable and provide an event handling mechanism.The simplest way to utilize Iteminterface is to use existing implementations. Provided utility classes include a configurable propertyset (PropertysetItem) and a bean-to-item adapter (BeanItem). Also, a Form implements theinterface and can therefore be used directly as an item.

In addition to being used indirectly by many user interface components, items provide the basicdata model underlying the Form component. In simple cases, forms can even be generatedautomatically from items. The properties of the item correspond to the fields of the form.

The Item interface defines inner interfaces for maintaining the item property set and listeningchanges made to it. PropertySetChangeEvent events can be emitted by a class implementingthe PropertySetChangeNotifier interface. They can be received through thePropertySetChangeListener interface.

9.3.1.The PropertysetItem Implementation

The PropertysetItem is a generic implementation of the Item interface that allows storingproperties. The properties are added with addItemProperty(), which takes a name and theproperty as parameters.

The following example demonstrates a typical case of collecting ObjectProperty properties inan item:

PropertysetItem item = new PropertysetItem();item.addItemProperty("name", new ObjectProperty("Zaphod"));item.addItemProperty("age", new ObjectProperty(42));

305Holding properties in Items

Binding Components to Data

Page 308: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Bind it to a componentForm form = new Form();form.setItemDataSource(item);

9.3.2. Wrapping a Bean in a BeanItem

The BeanItem implementation of the Item interface is a wrapper for Java Bean objects. In fact,only the setters and getters are required while serialization and other bean features are not, soyou can wrap almost any POJOs with minimal requirements.

// Here is a bean (or more exactly a POJO)class Person { String name; int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public Integer getAge() { return age; }

public void setAge(Integer age) { this.age = age.intValue(); }}

// Create an instance of the beanPerson bean = new Person();

// Wrap it in a BeanItemBeanItem<Person> item = new BeanItem<Person>(bean);

// Bind it to a componentForm form = new Form();form.setItemDataSource(item);

You can use the getBean() method to get a reference to the underlying bean.

Nested Beans

You may often have composite classes where one class "has a" another class. For example,consider the following Planet class which "has a" discoverer:

// Here is a bean with two nested beanspublic class Planet implements Serializable { String name; Person discoverer;

public Planet(String name, Person discoverer) { this.name = name; this.discoverer = discoverer; }

Wrapping a Bean in a BeanItem306

Binding Components to Data

Page 309: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

... getters and setters ...}

...// Create an instance of the beanPlanet planet = new Planet("Uranus", new Person("William Herschel", 1738));

When shown in a Form, for example, you would want to list the properties of the nested beanalong the properties of the composite bean. You can do that by binding the properties of thenested bean individually with a MethodProperty or NestedMethodProperty.You should usuallyhide the nested bean from binding as a property by listing only the bound properties in theconstructor.

// Wrap it in a BeanItem and hide the nested bean propertyBeanItem<Planet> item = new BeanItem<Planet>(planet, new String[]{"name"});

// Bind the nested properties.// Use NestedMethodProperty to bind using dot notation.item.addItemProperty("discoverername", new NestedMethodProperty(planet, "discoverer.name"));

// The other way is to use regular MethodProperty.item.addItemProperty("discovererborn", new MethodProperty<Person>(planet.getDiscoverer(), "born"));

The difference is that NestedMethodProperty does not access the nested bean immediatelybut only when accessing the property values, while when using MethodProperty the nestedbean is accessed when creating the method property. The difference is only significant if thenested bean can be null or be changed later.

You can use such a bean item for example in a Form as follows:

// Bind it to a componentForm form = new Form();form.setItemDataSource(item);

// Nicer captionsform.getField("discoverername").setCaption("Discoverer");form.getField("discovererborn").setCaption("Born");

Figura 9.3. A Form with Nested Bean Properties

The BeanContainer and BeanItemContainer allow easy definition of nested bean propertieswith addNestedContainerProperty(), as described in “Nested Properties”.

307Wrapping a Bean in a BeanItem

Binding Components to Data

Page 310: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

9.4. Creating Forms by Binding Fields to Items

Because of pressing release schedules to get this edition to your hands, we were unable tocompletely update this chapter. Some form handling is still under work, especially form validation.

Most applications in existence have forms of some sort. Forms contain fields, which you want tobind to a data source, an item in the Vaadin data model. FieldGroup provides an easy way tobind fields to the properties of an item. You can use it by first creating a layout with some fields,and then call it to bind the fields to the data source. You can also let the FieldGroup create thefields using a field factory. It can also handle commits. Notice that FieldGroup is not a userinterface component, so you can not add it to a layout.

9.4.1. Simple Binding

Let us start with a data model that has an item with a couple of properties.The item could be anyitem type, as described earlier.

// Have an itemPropertysetItem item = new PropertysetItem();item.addItemProperty("name", new ObjectProperty<String>("Zaphod"));item.addItemProperty("age", new ObjectProperty<Integer>(42));

Next, you would design a form for editing the data.The FormLayout (Secção 6.5, “FormLayout”is ideal for forms, but you could use any other layout as well.

// Have some layout and create the fieldsFormLayout form = new FormLayout();

TextField nameField = new TextField("Name");form.addComponent(nameField);

TextField ageField = new TextField("Age");form.addComponent(ageField);

Then, we can bind the fields to the data as follows:

// Now create the binder and bind the fieldsFieldGroup binder = new FieldGroup(item);binder.bind(nameField, "name");binder.bind(ageField, "age");

The above way of binding is not different from simply calling setPropertyDataSource() forthe fields. It does, however, register the fields in the field group, which for example enablesbuffering or validation of the fields using the field group, as described in Secção 9.4.4, “BufferingForms”.

Next, we consider more practical uses for a FieldGroup.

9.4.2. Using a FieldFactory to Build and Bind Fields

Using the buildAndBind() methods, FieldGroup can create fields for you using aFieldGroupFieldFactory, but you still have to add them to the correct position in your layout.

// Have some layoutFormLayout form = new FormLayout();

// Now create a binder that can also create the fields

Creating Forms by Binding Fields to Items308

Binding Components to Data

Page 311: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// using the default field factoryFieldGroup binder = new FieldGroup(item);form.addComponent(binder.buildAndBind("Name", "name"));form.addComponent(binder.buildAndBind("Age", "age"));

9.4.3. Binding Member Fields

The bindMemberFields() method in FieldGroup uses reflection to bind the properties of anitem to field components that are member variables of a class. Hence, if you implement a formas a class with the fields stored as member variables, you can use this method to bind themsuper-easy.

The item properties are mapped to the members by the property ID and the name of the membervariable. If you want to map a property with a different ID to a member, you can use the@PropertyId annotation for the member, with the property ID as the parameter.

For example:

// Have an itemPropertysetItem item = new PropertysetItem();item.addItemProperty("name", new ObjectProperty<String>("Zaphod"));item.addItemProperty("age", new ObjectProperty<Integer>(42));

// Define a form as a class that extends some layoutclass MyForm extends FormLayout { // Member that will bind to the "name" property TextField name = new TextField("Name");

// Member that will bind to the "age" property @PropertyId("age") TextField ageField = new TextField("Age");

public MyForm() { // Customize the layout a bit setSpacing(true);

// Add the fields addComponent(name); addComponent(ageField); }}

// Create oneMyForm form = new MyForm();

// Now create a binder that can also creates the fields// using the default field factoryFieldGroup binder = new FieldGroup(item);binder.bindMemberFields(form);

// And the form can be used in an higher-level layoutlayout.addComponent(form);

Encapsulating in CustomComponent

Using a CustomComponent can be better for hiding the implementation details than extendinga layout. Also, the use of the FieldGroup can be encapsulated in the form class.

309Binding Member Fields

Binding Components to Data

Page 312: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Consider the following as an alternative for the form implementation presented earlier:

// A form component that allows editing an itemclass MyForm extends CustomComponent { // Member that will bind to the "name" property TextField name = new TextField("Name");

// Member that will bind to the "age" property @PropertyId("age") TextField ageField = new TextField("Age");

public MyForm(Item item) { FormLayout layout = new FormLayout(); layout.addComponent(name); layout.addComponent(ageField);

// Now use a binder to bind the members FieldGroup binder = new FieldGroup(item); binder.bindMemberFields(this);

setCompositionRoot(layout); }}

// And the form can be used as a componentlayout.addComponent(new MyForm(item));

9.4.4. Buffering Forms

Just like for individual fields, as described in Secção 5.4.4, “Field Buffering”, a FieldGroup canhandle buffering the form content so that it is written to the item data source only when commit()is called for the group. It runs validation for all fields in the group and writes their values to theitem data source only if all fields pass the validation. Edits can be discarded, so that the fieldvalues are reloaded from the data source, by calling discard(). Buffering is enabled by default,but can be disabled by calling setBuffered(false) for the FieldGroup.

// Have an item of some sortfinal PropertysetItem item = new PropertysetItem();item.addItemProperty("name", new ObjectProperty<String>("Q"));item.addItemProperty("age", new ObjectProperty<Integer>(42));

// Have some layout and create the fieldsPanel form = new Panel("Buffered Form");form.setContent(new FormLayout());

// Build and bind the fields using the default field factoryfinal FieldGroup binder = new FieldGroup(item);form.addComponent(binder.buildAndBind("Name", "name"));form.addComponent(binder.buildAndBind("Age", "age"));

// Enable buffering (actually enabled by default)binder.setBuffered(true);

// A button to commit the bufferform.addComponent(new Button("OK", new ClickListener() { @Override public void buttonClick(ClickEvent event) { try { binder.commit();

Buffering Forms310

Binding Components to Data

Page 313: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Notification.show("Thanks!"); } catch (CommitException e) { Notification.show("You fail!"); } }}));

// A button to discard the bufferform.addComponent(new Button("Discard", new ClickListener() { @Override public void buttonClick(ClickEvent event) { binder.discard(); Notification.show("Discarded!"); }}));

9.4.5. Binding Fields to a Bean

The BeanFieldGroup makes it easier to bind fields to a bean. It also handles binding to nestedbeans properties. The build a field bound to a nested bean property, identify the property withdot notation. For example, if a Person bean has a address property with an Address type,which in turn has a street property, you could build a field bound to the property withbuildAndBind("Street", "address.street").

The input to fields bound to a bean can be validated using the Java Bean Validation API, asdescribed in Secção 9.4.6, “Bean Validation”. The BeanFieldGroup automatically adds aBeanValidator to every field if a bean validation implementation is included in the classpath.

9.4.6. Bean Validation

Vaadin allows using the Java Bean Validation API 1.0 (JSR-303) for validating input from fieldsbound to bean properties before the values are committed to the bean. The validation is donebased on annotations on the bean properties, which are used for creating the actual validatorsautomatically. See Secção 5.4.5, “Field Validation” for general information about validation.

Using bean validation requires an implementation of the Bean Validation API, such as HibernateValidator (hibernate-validator-4.2.0.Final.jar or later) or Apache Bean Validation.The implementation JAR must be included in the project classpath when using the bean validation,or otherwise an internal error is thrown.

Bean validation is especially useful when persisting entity beans with the Vaadin JPAContainer,described in Capítulo 19, Vaadin JPAContainer.

Annotations

The validation constraints are defined as annotations. For example, consider the following bean:

// Here is a beanpublic class Person implements Serializable { @NotNull @javax.validation.constraints.Size(min=2, max=10) String name;

@Min(1) @Max(130) int age;

311Binding Fields to a Bean

Binding Components to Data

Page 314: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// ... setters and getters ...}

For a complete list of allowed constraints for different data types, please see the Bean ValidationAPI documentation.

Validating the Beans

Validating a bean is done with a BeanValidator, which you initialize with the name of the beanproperty it should validate and add it the the editor field.

In the following example, we validate a single unbuffered field:

Person bean = new Person("Mung bean", 100);BeanItem<Person> item = new BeanItem<Person> (bean);

// Create an editor bound to a bean fieldTextField firstName = new TextField("First Name", item.getItemProperty("name"));

// Add the bean validatorfirstName.addValidator(new BeanValidator(Person.class, "name"));

firstName.setImmediate(true);layout.addComponent(firstName);

In this case, the validation is done immediately after focus leaves the field. You could do thesame for the other field as well.

Bean validators are automatically created when using a BeanFieldGroup.

// Have a beanPerson bean = new Person("Mung bean", 100);

// Form for editing the beanfinal BeanFieldGroup<Person> binder = new BeanFieldGroup<Person>(Person.class);binder.setItemDataSource(bean);layout.addComponent(binder.buildAndBind("Name", "name"));layout.addComponent(binder.buildAndBind("Age", "age"));

// Buffer the form contentbinder.setBuffered(true);layout.addComponent(new Button("OK", new ClickListener() { @Override public void buttonClick(ClickEvent event) { try { binder.commit(); } catch (CommitException e) { } }}));

Locale Setting for Bean Validation

The validation error messages are defined in the bean validation implementation, in aValidationMessages.properties file. The message is shown in the language specifiedwith the locale setting for the form. The default language is English, but for example Hibernate

Bean Validation312

Binding Components to Data

Page 315: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Validator contains translations of the messages for a number of languages. If other languagesare needed, you need to provide a translation of the properties file.

9.5. Collecting Items in Containers

The Container interface is the highest containment level of the Vaadin data model, for containingitems (rows) which in turn contain properties (columns). Containers can therefore representtabular data, which can be viewed in a Table or some other selection component, as well ashierarchical data.

The items contained in a container are identified by an item identifier or IID, and the propertiesby a property identifier or PID.

9.5.1. Basic Use of Containers

The basic use of containers involves creating one, adding items to it, and binding it as a containerdata source of a component.

Default Containers and Delegation

Before saying anything about creation of containers, it should be noted that all components thatcan be bound to a container data source are by default bound to a default container. For example,Table is bound to a IndexedContainer, Tree to a HierarchicalContainer, and so forth.

All of the user interface components using containers also implement the relevant containerinterfaces themselves, so that the access to the underlying data source is delegated through thecomponent.

// Create a table with one columnTable table = new Table("My Table");table.addContainerProperty("col1", String.class, null);

// Access items and properties through the componenttable.addItem("row1"); // Create item by explicit IDItem item1 = table.getItem("row1");Property property1 = item1.getItemProperty("col1");property1.setValue("some given value");

// Equivant access through the containerContainer container = table.getContainerDataSource();container.addItem("row2");Item item2 = container.getItem("row2");Property property2 = item2.getItemProperty("col1");property2.setValue("another given value");

Creating and Binding a Container

A container is created and bound to a component as follows:

// Create a containerContainer container = new IndexedContainer();

// Define the properties (columns) if required by containercontainer.addContainerProperty("name", String.class, "none");container.addContainerProperty("volume", Double.class, 0.0);

... add items ...

313Collecting Items in Containers

Binding Components to Data

Page 316: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Bind it to a componentTable table = new Table("My Table");table.setContainerDataSource(container);

Most components also allow passing the container in the constructor. Creation depends on thecontainer type. For some containers, such as the IndexedContainer, you need to define thecontained properties (columns) as was done above, while some others determine them otherwise.The definition of a property with addContainerProperty() requires a unique property ID,type, and a default value.You can also give null.

Vaadin has a several built-in in-memory container implementations, such as IndexedContainerand BeanItemContainer, which are easy to use for setting up nonpersistent data storages. Forpersistent data, either the built-in SQLContainer or the JPAContainer add-on container can beused.

Adding Items and Accessing Properties

Items can be added to a container with the addItem() method. The parameterless version ofthe method automatically generates the item ID.

// Create an itemObject itemId = container.addItem();

Properties can be requested from container by first requesting an item with getItem() and thengetting the properties from the item with getItemProperty().

// Get the item objectItem item = container.getItem(itemId);

// Access a property in the itemProperty<String> nameProperty = item.getItemProperty("name");

// Do something with the propertynameProperty.setValue("box");

You can also get a property directly by the item and property ids withgetContainerProperty().

container.getContainerProperty(itemId, "volume").setValue(5.0);

Adding Items by Given ID

Some containers, such as IndexedContainer and HierarchicalContainer, allow adding itemsby a given ID, which can be any Object.

Item item = container.addItem("agivenid");item.getItemProperty("name").setValue("barrel");Item.getItemProperty("volume").setValue(119.2);

Notice that the actual item is not given as a parameter to the method, only its ID, as the interfaceassumes that the container itself creates all the items it contains. Some container implementationscan provide methods to add externally created items, and they can even assume that the itemID object is also the item itself. Lazy containers might not create the item immediately, but lazilywhen it is accessed by its ID.

Basic Use of Containers314

Binding Components to Data

Page 317: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

9.5.2. Container Subinterfaces

The Container interface contains inner interfaces that container implementations can implementto fulfill different features required by components that present container data.

Container.FilterableFilterable containers allow filtering the contained items by filters, as described inSecção 9.5.7, “Filterable Containers”.

Container.HierarchicalHierarchical containers allow representing hierarchical relationships between itemsand are required by the Tree and TreeTable components.The HierarchicalContaineris a built-in in-memory container for hierarchical data, and is used as the defaultcontainer for the tree components. The FilesystemContainer provides access tobrowsing the content of a file system. Also JPAContainer is hierarchical, as describedin Secção 19.4.4, “Hierarchical Container”.

Container.IndexedAn indexed container allows accessing items by an index number, not just their itemID. This feature is required by some components, especially Table, which needs toprovide lazy access to large containers. The IndexedContainer is a basic in-memoryimplementation, as described in Secção 9.5.3, “IndexedContainer”.

Container.OrderedAn ordered container allows traversing the items in successive order in either direction.Most built-in containers are ordered.

Container.SimpleFilterableThis interface enables filtering a container by string matching withaddContainerFilter(). The filtering is done by either searching the given stringanywhere in a property value, or as its prefix.

Container.SortableA sortable container is required by some components that allow sorting the content,such as Table, where the user can click a column header to sort the table by thecolumn. Some other components, such as Calendar, may require that the content issorted to be able to display it properly. Depending on the implementation, sorting canbe done only when the sort() method is called, or the container is automatically keptin order according to the last call of the method.

See the API documentation for a detailed description of the interfaces.

9.5.3. IndexedContainer

The IndexedContainer is an in-memory container that implements the Indexed interface toallow referencing the items by an index. IndexedContainer is used as the default container inmost selection components in Vaadin.

The properties need to be defined with addContainerProperty(), which takes the propertyID, type, and a default value. This must be done before any items are added to the container.

// Create the containerIndexedContainer container = new IndexedContainer();

// Define the properties (columns)

315Container Subinterfaces

Binding Components to Data

Page 318: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

container.addContainerProperty("name", String.class, "noname");container.addContainerProperty("volume", Double.class, -1.0d);

// Add some itemsObject content[][] = {{"jar", 2.0}, {"bottle", 0.75}, {"can", 1.5}};for (Object[] row: content) { Item newItem = container.getItem(container.addItem()); newItem.getItemProperty("name").setValue(row[0]); newItem.getItemProperty("volume").setValue(row[1]);}

New items are added with addItem(), which returns the item ID of the new item, or by givingthe item ID as a parameter as was described earlier. Note that the Table component, which hasIndexedContainer as its default container, has a conveniency addItem() method that allowsadding items as object vectors containing the property values.

The container implements the Container.Indexed feature to allow accessing the item IDs bytheir index number, with getIdByIndex(), etc. The feature is required mainly for internalpurposes of some components, such as Table, which uses it to enable lazy transmission of tabledata to the client-side.

9.5.4. BeanContainer

The BeanContainer is an in-memory container for JavaBean objects. Each contained bean iswrapped inside a BeanItem wrapper. The item properties are determined automatically byinspecting the getter and setter methods of the class.This requires that the bean class has publicvisibility, local classes for example are not allowed. Only beans of the same type can be addedto the container.

The generic has two parameters: a bean type and an item identifier type.The item identifiers canbe obtained by defining a custom resolver, using a specific item property for the IDs, or by givingitem IDs explicitly. As such, it is more general than the BeanItemContainer, which uses the beanobject itself as the item identifier, making the use usually simpler. Managing the item IDs makesBeanContainer more complex to use, but it is necessary in some cases where the equals()or hashCode() methods have been reimplemented in the bean.

// Here is a JavaBeanpublic class Bean implements Serializable { String name; double energy; // Energy content in kJ/100g

public Bean(String name, double energy) { this.name = name; this.energy = energy; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public double getEnergy() { return energy;

BeanContainer316

Binding Components to Data

Page 319: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

}

public void setEnergy(double energy) { this.energy = energy; }}

void basic(VerticalLayout layout) { // Create a container for such beans with // strings as item IDs. BeanContainer<String, Bean> beans = new BeanContainer<String, Bean>(Bean.class);

// Use the name property as the item ID of the bean beans.setBeanIdProperty("name");

// Add some beans to it beans.addBean(new Bean("Mung bean", 1452.0)); beans.addBean(new Bean("Chickpea", 686.0)); beans.addBean(new Bean("Lentil", 1477.0)); beans.addBean(new Bean("Common bean", 129.0)); beans.addBean(new Bean("Soybean", 1866.0));

// Bind a table to it Table table = new Table("Beans of All Sorts", beans); layout.addComponent(table);}

To use explicit item IDs, use the methods addItem(Object, Object),addItemAfter(Object, Object, Object), and addItemAt(int, Object, Object).

It is not possible to add additional properties to the container, except properties in a nested bean.

Nested Properties

If you have a nested bean with a 1:1 relationship inside a bean type contained in a BeanContaineror BeanItemContainer, you can add its properties to the container by specifying them withaddNestedContainerProperty(). The feature is defined at the level ofAbstractBeanContainer.

As with a top-level bean in a bean container, also a nested bean must have public visibility orotherwise an access exception is thrown. Intermediary getters returning a nested bean mustalways return a non-null value.

For example, assume that we have the following two beans with the first one nested inside thesecond one.

/** Bean to be nested */public class EqCoord implements Serializable { double rightAscension; /* In angle hours */ double declination; /* In degrees */

... constructor and setters and getters for the properties ...}

/** Bean containing a nested bean */public class Star implements Serializable { String name;

317BeanContainer

Binding Components to Data

Page 320: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

EqCoord equatorial; /* Nested bean */

... constructor and setters and getters for the properties ...}

After creating the container, you can declare the nested properties by specifying their propertyidentifiers with the addNestedContainerProperty() in dot notation.

// Create a container for beansfinal BeanItemContainer<Star> stars = new BeanItemContainer<Star>(Star.class);

// Declare the nested properties to be used in the containerstars.addNestedContainerProperty("equatorial.rightAscension");stars.addNestedContainerProperty("equatorial.declination");

// Add some itemsstars.addBean(new Star("Sirius", new EqCoord(6.75, 16.71611)));stars.addBean(new Star("Polaris", new EqCoord(2.52, 89.26417)));

If you bind such a container to a Table, you probably also need to set the column headers. Noticethat the entire nested bean itself is still a property in the container and would be displayed in itsown column. The toString() method is used for obtaining the displayed value, which is bydefault an object reference. You normally do not want this, so you can hide the column withsetVisibleColumns().

// Put them in a tableTable table = new Table("Stars", stars);table.setColumnHeader("equatorial.rightAscension", "RA");table.setColumnHeader("equatorial.declination", "Decl");table.setPageLength(table.size());

// Have to set explicitly to hide the "equatorial" propertytable.setVisibleColumns(new Object[]{"name", "equatorial.rightAscension", "equatorial.declination"});

The resulting table is shown in Figura 9.4, “Table Bound to a BeanContainer with NestedProperties”.

Figura 9.4. Table Bound to a BeanContainer with Nested Properties

The bean binding in AbstractBeanContainer normally uses the MethodProperty implementationof the Property interface to access the bean properties using the setter and getter methods. Fornested properties, the NestedMethodProperty implementation is used.

Defining a Bean ID Resolver

If a bean ID resolver is set using setBeanIdResolver() or setBeanIdProperty(), themethods addBean(), addBeanAfter(), addBeanAt() and addAll() can be used to add

BeanContainer318

Binding Components to Data

Page 321: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

items to the container. If one of these methods is called, the resolver is used to generate anidentifier for the item (must not return null).

Note that explicit item identifiers can also be used when a resolver has been set by calling theaddItem*() methods - the resolver is only used when adding beans using the addBean*()or addAll(Collection) methods.

9.5.5. BeanItemContainer

BeanItemContainer is a container for JavaBean objects where each bean is wrapped inside aBeanItem wrapper. The item properties are determined automatically by inspecting the getterand setter methods of the class.This requires that the bean class has public visibility, local classesfor example are not allowed. Only beans of the same type can be added to the container.

BeanItemContainer is a specialized version of the BeanContainer described in Secção 9.5.4,“BeanContainer”. It uses the bean itself as the item identifier, which makes it a bit easier to usethan BeanContainer in many cases.The latter is, however, needed if the bean has reimplementedthe equals() or hashCode() methods.

Let us revisit the example given in Secção 9.5.4, “BeanContainer” using the BeanItemContainer.

// Create a container for the beansBeanItemContainer<Bean> beans = new BeanItemContainer<Bean>(Bean.class);

// Add some beans to itbeans.addBean(new Bean("Mung bean", 1452.0));beans.addBean(new Bean("Chickpea", 686.0));beans.addBean(new Bean("Lentil", 1477.0));beans.addBean(new Bean("Common bean", 129.0));beans.addBean(new Bean("Soybean", 1866.0));

// Bind a table to itTable table = new Table("Beans of All Sorts", beans);

It is not possible to add additional properties to a BeanItemContainer, except properties in anested bean, as described in Secção 9.5.4, “BeanContainer”.

9.5.6. Iterating Over a Container

As the items in a Container are not necessarily indexed, iterating over the items has to be doneusing an Iterator. The getItemIds() method of Container returns a Collection of itemidentifiers over which you can iterate. The following example demonstrates a typical case whereyou iterate over the values of check boxes in a column of a Table component. The context of theexample is the example used in Secção 5.16, “Table”.

// Collect the results of the iteration into this string.String items = "";

// Iterate over the item identifiers of the table.for (Iterator i = table.getItemIds().iterator(); i.hasNext();) { // Get the current item identifier, which is an integer. int iid = (Integer) i.next();

// Now get the actual item from the table. Item item = table.getItem(iid);

319BeanItemContainer

Binding Components to Data

Page 322: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// And now we can get to the actual checkbox object. Button button = (Button) (item.getItemProperty("ismember").getValue());

// If the checkbox is selected. if ((Boolean)button.getValue() == true) { // Do something with the selected item; collect the // first names in a string. items += item.getItemProperty("First Name") .getValue() + " "; }}

// Do something with the results; display the selected items.layout.addComponent (new Label("Selected items: " + items));

Notice that the getItemIds() returns an unmodifiable collection, so the Container may not bemodified during iteration. You can not, for example, remove items from the Container duringiteration. The modification includes modification in another thread. If the Container is modifiedduring iteration, a ConcurrentModificationException is thrown and the iterator may be left inan undefined state.

9.5.7. Filterable Containers

Containers that implement the Container.Filterable interface can be filtered. For example, thebuilt-in IndexedContainer and the bean item containers implement it. Filtering is typically usedfor filtering the content of a Table.

Filters implement the Filter interface and you add them to a filterable container with theaddContainerFilter() method. Container items that pass the filter condition are kept andshown in the filterable component.

Filter filter = new SimpleStringFilter("name", "Douglas", true, false);table.addContainerFilter(filter);

If multiple filters are added to a container, they are evaluated using the logical AND operator sothat only items that are passed by all the filters are kept.

Atomic and Composite Filters

Filters can be classified as atomic and composite. Atomic filters, such as SimpleStringFilter,define a single condition, usually for a specific container property. Composite filters make filteringdecisions based on the result of one or more other filters.The built-in composite filters implementthe logical operators AND, OR, or NOT.

For example, the following composite filter would filter out items where the name property containsthe name "Douglas" somewhere and where the age property has value less than 42. Theproperties must have String and Integer types, respectively.

filter = new Or(new SimpleStringFilter("name", "Douglas", true, false), new Compare.Less("age", 42));

Filterable Containers320

Binding Components to Data

Page 323: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Built-In Filter Types

The built-in filter types are the following:

SimpleStringFilter

Passes items where the specified property, that must be of String type, contains thegiven filterString as a substring. If ignoreCase is true, the search is caseinsensitive. If the onlyMatchPrefix is true, the substring may only be in thebeginning of the string, otherwise it may be elsewhere as well.

IsNull

Passes items where the specified property has null value. For in-memory filtering, asimple == check is performed. For other containers, the comparison implementationis container dependent, but should correspond to the in-memory null check.

Equal, Greater, Less, GreaterOrEqual, and LessOrEqual

The comparison filter implementations compare the specified property value to thegiven constant and pass items for which the comparison result is true.The comparisonoperators are included in the abstract Compare class.

For the Equal filter, the equals() method for the property is used in built-in in-memorycontainers. In other types of containers, the comparison is container dependent andmay use, for example, database comparison operations.

For the other filters, the property value type must implement the Comparable interfaceto work with the built-in in-memory containers. Again for the other types of containers,the comparison is container dependent.

And and Or

These logical operator filters are composite filters that combine multiple other filters.

Not

The logical unary operator filter negates which items are passed by the filter given asthe parameter.

Implementing Custom Filters

A custom filter needs to implement the Container.Filter interface.

A filter can use a single or multiple properties for the filtering logic. The properties used by thefilter must be returned with the appliesToProperty() method. If the filter applies to a user-defined property or properties, it is customary to give the properties as the first argument for theconstructor of the filter.

class MyCustomFilter implements Container.Filter { protected String propertyId; protected String regex;

public MyCustomFilter(String propertyId, String regex) { this.propertyId = propertyId; this.regex = regex; }

321Filterable Containers

Binding Components to Data

Page 324: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

/** Tells if this filter works on the given property. */ @Override public boolean appliesToProperty(Object propertyId) { return propertyId != null && propertyId.equals(this.propertyId); }

The actual filtering logic is done in the passesFilter() method, which simply returns true ifthe item should pass the filter and false if it should be filtered out.

/** Apply the filter on an item to check if it passes. */ @Override public boolean passesFilter(Object itemId, Item item) throws UnsupportedOperationException { // Acquire the relevant property from the item object Property p = item.getItemProperty(propertyId);

// Should always check validity if (p == null || !p.getType().equals(String.class)) return false; String value = (String) p.getValue();

// The actual filter logic return value.matches(regex); }}

You can use such a custom filter just like any other:

c.addContainerFilter( new MyCustomFilter("Name", (String) tf.getValue()));

Filterable Containers322

Binding Components to Data

Page 325: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 10

VaadinSQLContainer

10.1. Architecture ......................................................................................... 32410.2. Getting Started with SQLContainer ..................................................... 32410.3. Filtering and Sorting ............................................................................ 32510.4. Editing .................................................................................................. 32610.5. Caching, Paging and Refreshing ......................................................... 32810.6. Referencing Another SQLContainer ................................................... 33010.7. Using FreeformQuery and FreeformStatementDelegate ................. 33110.8. Non-implemented methods of Vaadin container interfaces ................. 33210.9. Known Issues and Limitations ............................................................. 332

Vaadin SQLContainer is a container implementation that allows easy and customizable accessto data stored in various SQL-speaking databases.

SQLContainer supports two types of database access. Using TableQuery, the pre-made querygenerators will enable fetching, updating, and inserting data directly from the container into adatabase table - automatically, whereas FreeformQuery allows the developer to use their own,probably more complex query for fetching data and their own optional implementations for writing,filtering and sorting support - item and property handling as well as lazy loading will still be handledautomatically.

In addition to the customizable database connection options, SQLContainer also extends theVaadin Container interface to implement more advanced and more database-oriented filtering

323Book of Vaadin

Page 326: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

rules. Finally, the add-on also offers connection pool implementations for JDBC connectionpooling and JEE connection pooling, as well as integrated transaction support; auto-commit modeis also provided.

The purpose of this section is to briefly explain the architecture and some of the inner workingsof SQLContainer. It will also give the readers some examples on how to use SQLContainer intheir own applications. The requirements, limitations and further development ideas are alsodiscussed.

SQLContainer is available from the Vaadin Directory under the same unrestrictive Apache License2.0 as the Vaadin Framework itself.

10.1. Architecture

The architecture of SQLContainer is relatively simple. SQLContainer is the class implementingthe Vaadin Container interfaces and providing access to most of the functionality of this add-on.The standard Vaadin Property and Item interfaces have been implementd as the ColumnPropertyand RowItem classes. Item IDs are represented by RowId and TemporaryRowId classes. TheRowId class is built based on the primary key columns of the connected database table or queryresult.

In the connection package, the JDBCConnectionPool interface defines the requirements for aconnection pool implementation. Two implementations of this interface are provided:SimpleJDBCConnectionPool provides a simple yet very usable implementation to pool andaccess JDBC connections. J2EEConnectionPool provides means to access J2EE DataSources.

The query package contains the QueryDelegate interface, which defines everything theSQLContainer needs to enable reading and writing data to and from a database. As discussedearlier, two implementations of this interface are provided: TableQuery for automatic read-writesupport for a database table, and FreeformQuery for customizing the query, sorting, filteringand writing; this is done by implementing relevant methods of the FreeformStatementDelegateinterface.

The query package also contains Filter and OrderBy classes which have been written to providean alternative to the standard Vaadin container filtering and make sorting non-String propertiesa bit more user friendly.

Finally, the generator package contains a SQLGenerator interface, which defines the kind ofqueries that are required by the TableQuery class.The provided implementations include supportfor HSQLDB, MySQL, PostgreSQL (DefaultSQLGenerator), Oracle (OracleGenerator) andMicrosoft SQL Server (MSSQLGenerator). A new or modified implementations may be providedto gain compatibility with older versions or other database servers.

For further details, please refer to the SQLContainer API documentation.

10.2. Getting Started with SQLContainer

Getting development going with the SQLContainer is easy and quite straight-forward.The purposeof this section is to describe how to create the required resources and how to fetch data fromand write data to a database table attached to the container.

Architecture324

Vaadin SQLContainer

Page 327: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

10.2.1. Creating a connection pool

First, we need to create a connection pool to allow the SQLContainer to connect to a database.Here we will use the SimpleJDBCConnectionPool, which is a basic implementation of connectionpooling with JDBC data sources. In the following code, we create a connection pool that usesthe HSQLDB driver together with an in-memory database. The initial amount of connections is2 and the maximum amount is set at 5. Note that the database driver, connection url, username,and password parameters will vary depending on the database you are using.

JDBCConnectionPool pool = new SimpleJDBCConnectionPool( "org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:mem:sqlcontainer", "SA", "", 2, 5);

10.2.2. Creating the TableQuery Query Delegate

After the connection pool is created, we'll need a query delegate for the SQLContainer. Thesimplest way to create one is by using the built-in TableQuery class. The TableQuery delegateprovides access to a defined database table and supports reading and writing data out-of-the-box.The primary key(s) of the table may be anything that the database engine supports, and arefound automatically by querying the database when a new TableQuery is instantiated.We createthe TableQuery with the following statement:

TableQuery tq = new TableQuery("tablename", connectionPool);

In order to allow writes from several user sessions concurrently, we must set a version columnto the TableQuery as well. The version column is an integer- or timestamp-typed column whichwill either be incremented or set to the current time on each modification of the row. TableQueryassumes that the database will take care of updating the version column; it just makes sure thecolumn value is correct before updating a row. If another user has changed the row and theversion number in the database does not match the version number in memory, anOptimisticLockException is thrown and you can recover by refreshing the container and allowthe user to merge the data. The following code will set the version column:

tq.setVersionColumn("OPTLOCK");

10.2.3. Creating the Container

Finally, we may create the container itself. This is as simple as stating:

SQLContainer container = new SQLContainer(tq);

After this statement, the SQLContainer is connected to the table tablename and is ready to usefor example as a data source for a Vaadin Table or a Vaadin Form.

10.3. Filtering and Sorting

Filtering and sorting the items contained in an SQLContainer is, by design, always performed inthe database. In practice this means that whenever the filtering or sorting rules are modified, atleast some amount of database communication will take place (the minimum is to fetch theupdated row count using the new filtering/sorting rules).

325Creating a connection pool

Vaadin SQLContainer

Page 328: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

10.3.1. Filtering

Filtering is performed using the filtering API in Vaadin, which allows for very complex filtering tobe easily applied. More information about the filtering API can be found in Secção 9.5.7, “FilterableContainers”.

In addition to the filters provided by Vaadin, SQLContainer also implements the Like filter as wellas the Between filter. Both of these map to the equally named WHERE-operators in SQL. Thefilters can also be applied on items that reside in memory, for example, new items that have notyet been stored in the database or rows that have been loaded and updated, but not yet stored.

The following is an example of the types of complex filtering that are possible with the new filteringAPI. We want to find all people named Paul Johnson that are either younger than 18 years orolder than 65 years and all Johnsons whose first name starts with the letter "A":

mySQLContainer.addContainerFilter( new Or(new And(new Equal("NAME", "Paul"), new Or(new Less("AGE", 18), new Greater("AGE", 65))), new Like("NAME", "A%")));mySQLContainer.addContainerFilter( new Equal("LASTNAME", "Johnson"));

This will produce the following WHERE clause:

WHERE (("NAME" = "Paul" AND ("AGE" < 18 OR "AGE" > 65)) OR "NAME" LIKE "A%") AND "LASTNAME" = "Johnson"

10.3.2. Sorting

Sorting can be performed using standard Vaadin, that is, using the sort method from theContainer.Sortable interface. The propertyId parameter refers to column names.

public void sort(Object[] propertyId, boolean[] ascending)

In addition to the standard method, it is also possible to directly add an OrderBy to the containervia the addOrderBy() method. This enables the developer to insert sorters one by one withoutproviding the whole array of them at once.

All sorting rules can be cleared by calling the sort method with null or an empty array as the firstargument.

10.4. Editing

Editing the items (RowItems) of SQLContainer can be done similarly to editing the items of anyVaadin container. ColumnProperties of a RowItem will automatically notify SQLContainer tomake sure that changes to the items are recorded and will be applied to the database immediatelyor on commit, depending on the state of the auto-commit mode.

10.4.1. Adding items

Adding items to an SQLContainer object can only be done via the addItem() method. Thismethod will create a new Item based on the connected database table column properties. Thenew item will either be buffered by the container or committed to the database through the querydelegate depending on whether the auto commit mode (see the next section) has been enabled.

Filtering326

Vaadin SQLContainer

Page 329: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

When an item is added to the container it is impossible to precisely know what the primary keysof the row will be, or will the row insertion succeed at all.This is why the SQLContainer will assignan instance of TemporaryRowId as a RowId for the new item. We will later describe how tofetch the actual key after the row insertion has succeeded.

If auto-commit mode is enabled in the SQLContainer, the addItem() methot will return thefinal RowId of the new item.

10.4.2. Fetching generated row keys

Since it is a common need to fetch the generated key of a row right after insertion, a listener/notifierhas been added into the QueryDelegate interface. Currently only the TableQuery classimplements the RowIdChangeNotifier interface, and thus can notify interested objects of changedrow IDs.The events fill be fired after commit() in TableQuery has finished; this method is calledby SQLContainer when necessary.

To receive updates on the row IDs, you might use the following code (assuming container is aninstance of SQLContainer). Note that these events are not fired if auto commit mode is enabled.

app.getDbHelp().getCityContainer().addListener( new QueryDelegate.RowIdChangeListener() { public void rowIdChange(RowIdChangeEvent event) { System.err.println("Old ID: " + event.getOldRowId()); System.err.println("New ID: " + event.getNewRowId()); } });

10.4.3. Version column requirement

If you are using the TableQuery class as the query delegate to the SQLContainer and need toenable write support, there is an enforced requirement of specifying a version column name tothe TableQuery instance. The column name can be set to the TableQuery using the followingstatement:

tq.setVersionColumn("OPTLOCK");

The version column is preferrably an integer or timestamp typed column in the table that isattached to the TableQuery. This column will be used for optimistic locking; before a rowmodification the TableQuery will check before that the version column value is the same as itwas when the data was read into the container. This should ensure that no one has modified therow inbetween the current user's reads and writes.

Note! TableQuery assumes that the database will take care of updating the version column byeither using an actual VERSION column (if supported by the database in question) or by a triggeror a similar mechanism.

If you are certain that you do not need optimistic locking, but do want to enable write support,you may point the version column to, for example, a primary key column of the table.

10.4.4. Auto-commit mode

SQLContainer is by default in transaction mode, which means that actions that edit, add orremove items are recorded internally by the container. These actions can be either committedto the database by calling commit() or discarded by calling rollback().

327Fetching generated row keys

Vaadin SQLContainer

Page 330: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The container can also be set to auto-commit mode. When this mode is enabled, all changes willbe committed to the database immediately. To enable or disable the auto-commit mode, call thefollowing method:

public void setAutoCommit(boolean autoCommitEnabled)

It is recommended to leave the auto-commit mode disabled, as it ensures that the changes canbe rolled back if any problems are noticed within the container items. Using the auto-commitmode will also lead to failure in item addition if the database table contains non-nullable columns.

10.4.5. Modified state

When used in the transaction mode it may be useful to determine whether the contents of theSQLContainer have been modified or not. For this purpose the container provides anisModified() method, which will tell the state of the container to the developer. This methodwill return true if any items have been added to or removed from the container, as well as if anyvalue of an existing item has been modified.

Additionally, each RowItem and each ColumnProperty have isModified() methods to allowfor a more detailed view over the modification status. Do note that the modification statuses ofRowItem and ColumnProperty objects only depend on whether or not the actual Propertyvalues have been modified. That is, they do not reflect situations where the whole RowItem hasbeen marked for removal or has just been added to the container.

10.5. Caching, Paging and Refreshing

To decrease the amount of queries made to the database, SQLContainer uses internal cachingfor database contents.The caching is implemented with a size-limited LinkedHashMap containinga mapping from RowIds to RowItems. Typically developers do not need to modify cachingoptions, although some fine-tuning can be done if required.

10.5.1. Container Size

The SQLContainer keeps continuously checking the amount of rows in the connected databasetable in order to detect external addition or removal of rows. By default, the table row count isassumed to remain valid for 10 seconds. This value can be altered from code; withsetSizeValidMilliSeconds() in SQLContainer.

If the size validity time has expired, the row count will be automatically updated on:

• A call to getItemIds() method

• A call to size() method

• Some calls to indexOfId(Object itemId) method

• A call to firstItemId() method

• When the container is fetching a set of rows to the item cache (lazy loading)

10.5.2. Page Length and Cache Size

The page length of the SQLContainer dictates the amount of rows fetched from the databasein one query. The default value is 100, and it can be modified with the setPageLength()method. To avoid constant queries it is recommended to set the page length value to at least 5

Modified state328

Vaadin SQLContainer

Page 331: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

times the amount of rows displayed in a Vaadin Table; obviously, this is also dependent on thecache ratio set for the Table component.

The size of the internal item cache of the SQLContainer is calculated by multiplying the pagelenght with the cache ratio set for the container. The cache ratio can only be set from the code,and the default value for it is 2. Hence with the default page length of 100 the internal cache sizebecomes 200 items. This should be enough even for larger Tables while ensuring that no hugeamounts of memory will be used on the cache.

10.5.3. Refreshing the Container

Normally, the SQLContainer will handle refreshing automatically when required. However, theremay be situations where an implicit refresh is needed, for example, to make sure that the versioncolumn is up-to-date prior to opening the item for editing in a form. For this purpose a refresh()method is provided. This method simply clears all caches, resets the current item fetching offsetand sets the container size dirty. Any item-related call after this will inevitably result into row countand item cache update.

Note that a call to the refresh method will not affect or reset the following properties of thecontainer:

• The QueryDelegate of the container

• Auto-commit mode

• Page length

• Filters

• Sorting

10.5.4. Cache Flush Notification Mechanism

Cache usage with databases in multiuser applications always results in some kind of a compromisebetween the amount of queries we want to execute on the database and the amount of memorywe want to use on caching the data; and most importantly, risking the cached data becomingstale.

SQLContainer provides an experimental remedy to this problem by implementing a simple cacheflush notification mechanism. Due to its nature these notifications are disabled by default but canbe easily enabled for a container instance by calling enableCacheFlushNotifications()at any time during the lifetime of the container.

The notification mechanism functions by storing a weak reference to all registered containers ina static list structure. To minimize the risk of memory leaks and to avoid unlimited growing of thereference list, dead weak references are collected to a reference queue and removed from thelist every time a SQLContainer is added to the notification reference list or a container calls thenotification method.

When a SQLContainer has its cache notifications set enabled, it will call the staticnotifyOfCacheFlush() method giving itself as a parameter. This method will compare thenotifier-container to all the others present in the reference list. To fire a cache flush event, thetarget container must have the same type of QueryDelegate (either TableQuery orFreeformQuery) and the table name or query string must match with the container that fired the

329Refreshing the Container

Vaadin SQLContainer

Page 332: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

notification. If a match is found the refresh() method of the matching container is called,resulting in cache flushing in the target container.

Note: Standard Vaadin issues apply; even if the SQLContainer is refreshed on the server side,the changes will not be reflected to the UI until a server round-trip is performed, or unless a pushmechanism is used.

10.6. Referencing Another SQLContainer

When developing a database-connected application, there is usually a need to retrieve datarelated to one table from one or more other tables. In most cases, this relation is achieved witha foreign key reference, where a column of the first table contains a primary key or candidatekey of a row in another table.

SQLContainer offers limited support for this kind of referencing relation, although all referencingis currently done on the Java side so no constraints need to be made in the database. A newreference can be created by calling the following method:

public void addReference(SQLContainer refdCont, String refingCol, String refdCol);

This method should be called on the source container of the reference. The target containershould be given as the first parameter. The refingCol is the name of the 'foreign key' columnin the source container, and the refdCol is the name of the referenced key column in the targetcontainer.

Note: For any SQLContainer, all the referenced target containers must be different.You can notreference the same container from the same source twice.

Handling the referenced item can be done through the three provided set/get methods, and thereference can be completely removed with the removeReference() method. Signatures ofthese methods are listed below:

public boolean setReferencedItem(Object itemId, Object refdItemId, SQLContainer refdCont)public Object getReferencedItemId(Object itemId, SQLContainer refdCont)public Item getReferencedItem(Object itemId, SQLContainer refdCont)public boolean removeReference(SQLContainer refdCont)

The setter method should be given three parameters: itemId is the ID of the referencing item(from the source container), refdItemId is the referenced itemID (from the target container)and refdCont is a reference to the target container that identifies the reference. This methodreturns true if the setting of the referenced item was successful. After setting the referenced itemyou must normally call commit() on the source container to persist the changes to the database.

The getReferencedItemId() method will return the item ID of the referenced item. Asparameters this method needs the item ID of the referencing item and a reference to the targetcontainer as an identifier. SQLContainer also provides a convenience methodgetReferencedItem(), which directly returns the referenced item from the target container.

Finally, the referencing can be removed from the source container by calling theremoveReference() method with the target container as parameter. Note that this does notactually change anything in the database; it merely removes the logical relation that exists onlyon the Java-side.

Referencing Another SQLContainer330

Vaadin SQLContainer

Page 333: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

10.7. Using FreeformQuery and FreeformStatementDelegate

In most cases, the provided TableQuery will be enough to allow a developer to gain effortlessaccess to an SQL data source. However there may arise situations when a more complex querywith, for example, join expressions is needed. Or perhaps you need to redefine how the writingor filtering should be done.The FreeformQuery query delegate is provided for this exact purpose.Out of the box the FreeformQuery supports read-only access to a database, but it can beextended to allow writing also.

10.7.1. Getting started

Getting started with the FreeformQuery may be done as shown in the following.The connectionpool initialization is similar to the TableQuery example so it is omitted here. Note that the name(s)of the primary key column(s) must be provided to the FreeformQuery manually. This is requiredbecause depending on the query the result set may or may not contain data about primary keycolumns. In this example, there is one primary key column with a name 'ID'.

FreeformQuery query = new FreeformQuery( "SELECT * FROM SAMPLE", pool, "ID");SQLContainer container = new SQLContainer(query);

10.7.2. Limitations

While this looks just as easy as with the TableQuery, do note that there are some importantcaveats here. Using FreeformQuery like this (without providing FreeformQueryDelegate orFreeformStatementDelegate implementation) it can only be used as a read-only window to theresultset of the query. Additionally filtering, sorting and lazy loading features will not be supported,and the row count will be fetched in quite an inefficient manner. Bearing these limitations in mind,it becomes quite obvious that the developer is in reality meant to implement theFreeformQueryDelegate or FreeformStatementDelegate interface.

The FreeformStatementDelegate interface is an extension of the FreeformQueryDelegateinterface, which returns StatementHelper objects instead of pure query Strings. This enablesthe developer to use prepared statetemens instead of regular statements. It is highly recommendedto use the FreeformStatementDelegate in all implementations. From this chapter onwards, wewill only refer to the FreeformStatementDelegate in cases where FreeformQueryDelegatecould also be applied.

10.7.3. Creating your own FreeformStatementDelegate

To create your own delegate for FreeformQuery you must implement some or all of the methodsfrom the FreeformStatementDelegate interface, depending on which ones your use caserequires. The interface contains eight methods which are shown below. For more detailedrequirements, see the JavaDoc documentation of the interface.

// Read-only queriespublic StatementHelper getCountStatement()public StatementHelper getQueryStatement(int offset, int limit)public StatementHelper getContainsRowQueryStatement(Object... keys)

// Filtering and sortingpublic void setFilters(List<Filter> filters)public void setFilters(List<Filter> filters, FilteringMode filteringMode)public void setOrderBy(List<OrderBy> orderBys)

331Using FreeformQuery and FreeformStatementDelegate

Vaadin SQLContainer

Page 334: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Write supportpublic int storeRow(Connection conn, RowItem row)public boolean removeRow(Connection conn, RowItem row)

A simple demo implementation of this interface can be found in the SQLContainer package, morespecifically in the class com.vaadin.addon.sqlcontainer.demo.DemoFreeformQueryDelegate.

10.8. Non-implemented methods of Vaadin container interfaces

Due to the database connection inherent to the SQLContainer, some of the methods from thecontainer interfaces of Vaadin can not (or would not make sense to) be implemented. Thesemethods are listed below, and they will throw an UnsupportedOperationException on invocation.

public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue)public boolean removeContainerProperty(Object propertyId)public Item addItem(Object itemId)public Object addItemAt(int index)public Item addItemAt(int index, Object newItemId)public Object addItemAfter(Object previousItemId)public Item addItemAfter(Object previousItemId, Object newItemId)

Additionally, the following methods of the Item interface are not supported in the RowItem class:

public boolean addItemProperty(Object id, Property property)public boolean removeItemProperty(Object id)

10.8.1. About the getItemIds() method

To properly implement the Vaadin Container interface, a getItemIds() method has beenimplented in the SQLContainer. By definition, this method returns a collection of all the item IDspresent in the container. What this means in the SQLContainer case is that the container hasto query the database for the primary key columns of all the rows present in the connecteddatabase table.

It is obvious that this could potentially lead to fetching tens or even hundreds of thousands ofrows in an effort to satisfy the method caller. This will effectively kill the lazy loading propertiesof SQLContainer and therefore the following warning is expressed here:

Atenção

It is highly recommended not to call the getitemIds() method, unless it is knownthat in the use case in question the item ID set will always be of reasonable size.

10.9. Known Issues and Limitations

At this point, there are still some known issues and limitations affecting the use of SQLContainerin certain situations. The known issues and brief explanations are listed below:

• Some SQL data types do not have write support when using TableQuery:

• All binary types

• All custom types

Non-implemented methods of Vaadin container interfaces332

Vaadin SQLContainer

Page 335: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

• CLOB (if not converted automatically to a String by the JDBC driver in use)

• See com.vaadin.addon.sqlcontainer.query.generator.StatementHelper for details.

• When using Oracle or MS SQL database, the column name "rownum" can not be usedas a column name in a table connected to SQLContainer.

This limitation exists because the databases in question do not support limit/offset clausesrequired for paging. Instead, a generated column named 'rownum' is used to implementpaging support.

The permanent limitations are listed below. These can not or most probably will not be fixed infuture versions of SQLContainer.

• The getItemIds() method is very inefficient - avoid calling it unless absolutely required!

• When using FreeformQuery without providing a FreeformStatementDelegate, the rowcount query is very inefficient - avoid using FreeformQuery without implementing atleast the count query properly.

• When using FreeformQuery without providing a FreeformStatementDelegate, writing,sorting and filtering will not be supported.

• When using Oracle database most or all of the numeric types are converted tojava.math.BigDecimal by the Oracle JDBC Driver.

This is a feature of how Oracle DB and the Oracle JDBC Driver handles data types.

333Known Issues and Limitations

Vaadin SQLContainer

Page 336: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

334

Page 337: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

bapítulo 11

Advanced WebApplication Topics

11.1. Handling Browser Windows ................................................................. 33611.2. Embedding UIs in Web Pages ............................................................. 33811.3. Debug Mode and Window .................................................................... 34611.4. Request Handlers ................................................................................ 35111.5. Shortcut Keys ...................................................................................... 35211.6. Printing ................................................................................................ 35611.7. Google App Engine Integration ........................................................... 35811.8. Common Security Issues ..................................................................... 35911.9. Navigating in an Application ................................................................ 36011.10. Advanced Application Architectures .................................................. 36411.11. Managing URI Fragments .................................................................. 36911.12. Drag and Drop ................................................................................... 37111.13. Logging .............................................................................................. 38011.14. JavaScript Interaction ........................................................................ 38111.15. Accessing Session-Global Data ........................................................ 38311.16. Server Push ....................................................................................... 38611.17. Font Icons .......................................................................................... 391

This chapter covers various features and topics often needed in applications.

335Book of Vaadin

Page 338: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

11.1. Handling Browser Windows

The UI of a Vaadin application runs in a web page displayed in a browser window or tab. Anapplication can be used from multiple UIs in different windows or tabs, either opened by the userusing an URL or by the Vaadin application.

In addition to native browser windows, Vaadin has a Window component, which is a floatingpanel or sub-window inside a page, as described in Secção 6.7, “Sub-Windows”.

• Native popup windows. An application can open popup windows for sub-tasks.

• Page-based browsing. The application can allow the user to open certain content todifferent windows. For example, in a messaging application, it can be useful to opendifferent messages to different windows so that the user can browse through them whilewriting a new message.

• Bookmarking. Bookmarks in the web browser can provide an entry-point to some contentprovided by an application.

• Embedding UIs. UIs can be embedded in web pages, thus making it possible to providedifferent views to an application from different pages or even from the same page, whilekeeping the same session. See Secção 11.2, “Embedding UIs in Web Pages”.

Use of multiple windows in an application may require defining and providing different UIs for thedifferent windows. The UIs of an application share the same user session, that is, theVaadinSession object, as described in Secção 4.7.3, “Sessão de Usuário”. Each UI is identifiedby a URL that is used to access it, which makes it possible to bookmark application UIs. UIinstances can even be created dynamically based on the URLs or other request parameters,such as browser information, as described in Secção 4.7.4, “Carregando uma UI”.

Because of the special nature of AJAX applications, use of multiple windows uses require somecaveats.

11.1.1. Opening Popup Windows

Popup windows are native browser windows or tabs opened by user interaction with an existingwindow. Due to browser security reasons, it is made incovenient for a web page to open popupwindows using JavaScript commands. At the least, the browser will ask for a permission to openthe popup, if it is possible at all. This limitation can be circumvented by letting the browser openthe new window or tab directly by its URL when the user clicks some target. This is realized inVaadin with the BrowserWindowOpener component extension, which causes the browser toopen a window or tab when the component is clicked.

The Popup Window UI

A popup Window displays an UI. The UI of a popup window is defined just like a main UI in aVaadin application, and it can have a theme, title, and so forth.

For example:

@Theme("book-examples")public static class MyPopupUI extends UI { @Override protected void init(VaadinRequest request) { getPage().setTitle("Popup Window");

Handling Browser Windows336

Advanced Web Application Topics

Page 339: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

// Have some content for it VerticalLayout content = new VerticalLayout(); Label label = new Label("I just popped up to say hi!"); label.setSizeUndefined(); content.addComponent(label); content.setComponentAlignment(label, Alignment.MIDDLE_CENTER); content.setSizeFull(); setContent(content); }}

Popping It Up

A popup window is opened using the BrowserWindowOpener extension, which you can attachto any component. The constructor of the extension takes the class object of the UI class to beopened as a parameter.

You can configure the features of the popup window with setFeatures(). It takes as itsparameter a comma-separated list of window features, as defined in the HTML specification.

status=0|1Whether the status bar at the bottom of the window should be enabled.

scrollbarsEnables scrollbars in the window if the document area is bigger than the view area ofthe window.

resizableAllows the user to resize the browser window (no effect for tabs).

menubarEnables the browser menu bar.

locationEnables the location bar.

toolbarEnables the browser toolbar.

height=valueSpecifies the height of the window in pixels.

width=valueSpecifies the width of the window in pixels.

For example:

// Create an opener extensionBrowserWindowOpener opener = new BrowserWindowOpener(MyPopupUI.class);opener.setFeatures("height=200,width=300,resizable");

// Attach it to a buttonButton button = new Button("Pop It Up");opener.extend(button);

337Opening Popup Windows

Advanced Web Application Topics

Page 340: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

The resulting popup window, which appears when the button is clicked, is shown in Figura 11.1,“A Popup Window”.

Figura 11.1. A Popup Window

Popup Window Name (Target)

The target name is one of the default HTML target names (_new, _blank, _top, etc.) or a customtarget name. How the window is exactly opened depends on the browser. Browsers that supporttabbed browsing can open the window in another tab, depending on the browser settings.

URL and Session

The URL path for a popup window UI is by default determined from the UI class name, by prefixigit with "popup/". For example, for the example UI giver earlier, the URL would be /book-examples/book/popup/MyPopupUI.

11.2. Embedding UIs in Web Pages

Many web sites are not all Vaadin, but Vaadin UIs are used only for specific functionalities. Inpractice, many web applications are a mixture of dynamic web pages, such as JSP, and VaadinUIs embedded in such pages.

Embedding Vaadin UIs in web pages is easy and there are several different ways to embed them.One is to have a <div> placeholder for the UI and load the Vaadin Client-Side Engine with somesimple JavaScript code. Another method is even easier, which is to simply use the <iframe>element. Both of these methods have advantages and disadvantages. One disadvantage of the<iframe> method is that the size of the <iframe> element is not flexible according to thecontent while the <div> method allows such flexibility. The following sections look closer intothese two embedding methods. Additionally, the Vaadin XS add-on allows embedding VaadinUIs in websites running in another server.

11.2.1. Embedding Inside a div Element

You can embed one or more Vaadin UIs inside a web page with a method that is equivalent toloading the initial page content from the Vaadin servlet in a non-embedded UI. Normally, theVaadinServlet generates an initial page that contains the correct parameters for the specific UI.You can easily configure it to load multiple Vaadin UIs in the same page. They can have differentwidget sets and different themes.

Embedding UIs in Web Pages338

Advanced Web Application Topics

Page 341: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Embedding an UI requires the following basic tasks:

• Set up the page header

• Include a GWT history frame in the page

• Call the vaadinBootstrap.js file

• Define the <div> element for the UI

• Configure and initialize the UI

Notice that you can view the loader page for the UI easily by opening the UI in a web browserand viewing the HTML source code of the page. You could just copy and paste the embeddingcode from the page, but some modifications and additional settings are required, mainly relatedto the URLs that have to be made relative to the page instead of the servlet URL.

The DIV embedding API is about to change soon after printing this book edition. A tutorial thatdescribes the feature should be made available at the Vaadin website.

The Head Matter

The HTML page in which the Vaadin UI is embedded should be a valid XHTML document, asdefined in the document type.The content of the head element is largely up to you.The characterencoding must be UTF-8. Some meta declarations are necessary for compatibility.You can alsoset the page favicon in the head element.

<!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=9;chrome=1" />

<title>This is my Embedding Page</title>

<!-- Set up the favicon from the Vaadin theme --> <link rel="shortcut icon" type="image/vnd.microsoft.icon" href="/VAADIN/themes/reindeer/favicon.ico" /> <link rel="icon" type="image/vnd.microsoft.icon" href="/VAADIN/themes/reindeer/favicon.ico" /> </head>

The Body Matter

The page content must include some Vaadin-related definitions before you can embed VaadinUIs in it.

The vaadinBootstrap.js script makes definitions for starting up the UI. It must be calledbefore initializing the UI. The source path must be relative to the path of the embedding page.

<body> <script type="text/javascript" src="./VAADIN/vaadinBootstrap.js"></script>

The bootstrap script is served by the Vaadin servlet from inside the vaadin-server JAR.

339Embedding Inside a div Element

Advanced Web Application Topics

Page 342: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Vaadin, or more precisely GWT, requires an invisible history frame, which is used for trackingthe page or fragment history in the browser.

<iframe tabindex="-1" id="__gwt_historyFrame" style="position: absolute; width: 0; height: 0; border: 0; overflow: hidden" src="javascript:false"></iframe>

UI Placeholder Element

A Vaadin UI is embedded in a placeholder <div> element. It should have the following features:

• The <div> element must have an id attribute, which must be a unique ID in the page,normally something that identifies the servlet of the UI uniquely.

• It must have at least the v-app style class.

• it should have a nested <div> element with v-app-loading style class. This is aplaceholder for the loading indicator that is displayed while the UI is being loaded.

• It should also contain a <noscript> element that is shown if the browser does notsupport JavaScript or it has been disabled. The content of the element should instructthe use to enable JavaScript in the browser.

The placeholder element can include style settings, typically a width and height. If the sizes arenot defined, the UI will have an undefined size in the particular dimension, which must be inaccordance with the sizing of the UI components.

For example:

<div style="width: 300px; border: 2px solid green;" id="helloworldui" class="v-app"> <div class="v-app-loading"></div> <noscript>You have to enable javascript in your browser to

use an application built with Vaadin.</noscript></div>

Initializing the UI

The UI is loaded by calling the initApplication() method for the vaadin object defined inthe bootstrap script. Before calling it, you should check that the bootstrap script was loadedproperly.

<script type="text/javascript">//<![CDATA[ if (!window.vaadin) alert("Failed to load the bootstrap JavaScript:"+ "VAADIN/vaadinBootstrap.js");

The initApplication() takes two parameters.The first parameter is the UI identifier, exactlyas given as the id attribute of the placeholder element. The second parameter is an associativemap that contains parameters for the UI.

The map must contain the following items:

Embedding Inside a div Element340

Advanced Web Application Topics

Page 343: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

browserDetailsUrlThis should be the URL path (relative to the embedding page) to the Vaadin servletof the UI. It is used by the bootstrap to communicate browser details. A trailing slashmay be needed in some cases.

Notice that this parameter is not included in the loader page generated by the servlet,because in that case, it can default to the current URL.

serviceUrlThis is used for server requests after initial loading and should be same as forbrowserDetailsUrl.The two parameters are redundant and either may be removedin future.

widgetsetThis should be the exact class name of the widget set for the UI, that is, without the.gwt.xml file name extension. If the UI has no custom widget set, you can use thecom.vaadin.DefaultWidgetSet.

themeName of the theme, such as one of the built-in themes (reindeer, runo, orchameleon) or a custom theme. It must exist under the VAADIN/themes folder.

versionInfoThis parameter is itself an associative map that can contain two parameters:vaadinVersion contains the version number of the Vaadin version used by theapplication. The applicationVersion parameter contains the version of theparticular application. The contained parameters are optional, but the versionInfoparameter itself is not.

vaadinDirRelative path to the VAADIN directory. It is relative to the URL of the embedding page.

heartbeatIntervalThe hearbeatInterval parameter defines the frequency of the keep-alive hearbeatfor the UI in seconds, as described in Secção 4.7.5, “Expiração de UI”.

debugThe parameter defines whether the debug window, as described in Secção 11.3,“Debug Mode and Window”, is enabled.

standaloneThis parameter should be false when embedding. The parameter defines whetherthe UI is rendered on its own in the browser window or in some context. A standaloneUI may do things that might interfere with other parts of the page, such as change thepage title and request focus when it is loaded. When embedding, the UI is notstandalone.

authErrMsg, comErrMsg, and sessExpMsgThese three parameters define the client-side error messages for authentication error,communication error, and session expiration, respectively. The parameters areassociative maps themselves and must contain two key-value pairs: message, whichshould contain the error text in HTML, and caption, which should be the error caption.

For example:

341Embedding Inside a div Element

Advanced Web Application Topics

Page 344: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

vaadin.initApplication("helloworldui", { "browserDetailsUrl": "helloworld/", "serviceUrl": "helloworld/", "widgetset": "com.example.MyWidgetSet", "theme": "mytheme", "versionInfo": {"vaadinVersion": "7.0.0"}, "vaadinDir": "VAADIN/", "heartbeatInterval": 300, "debug": true, "standalone": false, "authErrMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Authentication problem" }, "comErrMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Communication problem" }, "sessExpMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Session Expired" } });//]]></script>

Notice that many of the parameters are normally deployment parameters, specified in thedeployment descriptor, as described in Secção 4.8.6, “Outros Parâmetros de Configuração deServlet”.

Summary of Div Embedding

Below is a complete example of embedding an UI in a <div> element.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=9;chrome=1" />

<title>Embedding a Vaadin Application in HTML Page</title>

<!-- Set up the favicon from the Vaadin theme --> <link rel="shortcut icon" type="image/vnd.microsoft.icon" href="/VAADIN/themes/reindeer/favicon.ico" /> <link rel="icon" type="image/vnd.microsoft.icon" href="/VAADIN/themes/reindeer/favicon.ico" /> </head>

<body> <!-- Loads the Vaadin widget set, etc. --> <script type="text/javascript" src="VAADIN/vaadinBootstrap.js"></script>

Embedding Inside a div Element342

Advanced Web Application Topics

Page 345: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<!-- GWT requires an invisible history frame. It is --> <!-- needed for page/fragment history in the browser. --> <iframe tabindex="-1" id="__gwt_historyFrame" style="position: absolute; width: 0; height: 0; border: 0; overflow: hidden" src="javascript:false"></iframe>

<h1>Embedding a Vaadin UI</h1>

<p>This is a static web page that contains an embedded Vaadin application. It's here:</p>

<!-- So here comes the div element in which the Vaadin --> <!-- application is embedded. --> <div style="width: 300px; border: 2px solid green;" id="helloworld" class="v-app">

<!-- Optional placeholder for the loading indicator --> <div class=" v-app-loading"></div>

<!-- Alternative fallback text --> <noscript>You have to enable javascript in your browser to use an application built with Vaadin.</noscript> </div>

<script type="text/javascript">//<![CDATA[ if (!window.vaadin) alert("Failed to load the bootstrap JavaScript: "+ "VAADIN/vaadinBootstrap.js");

/* The UI Configuration */ vaadin.initApplication("helloworld", { "browserDetailsUrl": "helloworld/", "serviceUrl": "helloworld/", "widgetset": "com.example.MyWidgetSet", "theme": "mytheme", "versionInfo": {"vaadinVersion": "7.0.0"}, "vaadinDir": "VAADIN/", "heartbeatInterval": 300, "debug": true, "standalone": false, "authErrMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Authentication problem" }, "comErrMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Communication problem" }, "sessExpMsg": { "message": "Take note of any unsaved data, "+ "and <u>click here<\/u> to continue.", "caption": "Session Expired" } });//]] > </script>

343Embedding Inside a div Element

Advanced Web Application Topics

Page 346: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

<p>Please view the page source to see how embedding works.</p></body></html>

11.2.2. Embedding Inside an iframe Element

Embedding a Vaadin UI inside an <iframe> element is even easier than the method describedabove, as it does not require definition of any Vaadin specific definitions.

You can embed an UI with an element such as the following:

<iframe src="/myapp/myui"></iframe>

The <iframe> elements have several downsides for embedding. One is that their size of is notflexible depending on the content of the frame, but the content must be flexible to accommodatein the frame. You can set the size of an <iframe> element with height and width attributes.Other issues arise from themeing and communication with the frame content and the rest of thepage.

Below is a complete example of using the <iframe> to embed two applications in a web page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Embedding in IFrame</title> </head>

<body style="background: #d0ffd0;"> <h1>This is a HTML page</h1> <p>Below are two Vaadin applications embedded inside a table:</p>

<table align="center" border="3"> <tr> <th>The Calculator</th> <th>The Color Picker</th> </tr> <tr valign="top"> <td> <iframe src="/vaadin-examples/Calc" height="200" width="150" frameborder="0"></iframe> </td> <td> <iframe src="/vaadin-examples/colorpicker" height="330" width="400" frameborder="0"></iframe> </td> </tr> </table> </body></html>

The page will look as shown in Figura 11.2, “Vaadin Applications Embedded Inside IFrames”below.

Embedding Inside an iframe Element344

Advanced Web Application Topics

Page 347: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 11.2. Vaadin Applications Embedded Inside IFrames

You can embed almost anything in an iframe, which essentially acts as a browser window.However, this creates various problems. The iframe must have a fixed size, inheritance of CSSfrom the embedding page is not possible, and neither is interaction with JavaScript, which makesmashups impossible, and so on. Even bookmarking with URI fragments will not work.

Note also that websites can forbid iframe embedding by specifying an X-Frame-Options:SAMEORIGIN header in the HTTP response.

11.2.3. Cross-Site Embedding with the Vaadin XS Add-on

The XS add-on is not yet available for Vaadin 7.

In the previous sections, we described the two basic methods for embedding Vaadin applications:in a <div> element and in an <iframe>. One problem with div embedding is that it does notwork between different Internet domains, which is a problem if you want to have your websiterunning in one server and your Vaadin application in another. The security model in browserseffectively prevents such cross-site embedding of Ajax applications by enforcing the same originpolicy for XmlHttpRequest calls, even if the server is running in the same domain but differentport. While iframe is more permissive, allowing embedding almost anything in anywhere, it hasmany disadvantanges, as described earlier.

The Vaadin XS (Cross-Site) add-on works around the limitation in div embedding by using JSONP-style communication instead of the standard XmlHttpRequests.

Embedding is done simply with:

<script src="http://demo.vaadin.com/xsembed/getEmbedJs" type="text/javascript"></script>

345Cross-Site Embedding with the Vaadin XS Add-on

Advanced Web Application Topics

Page 348: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

This includes an automatically generated embedding script in the page, thereby making embeddingeffortless.

This assumes that the main layout of the application has undefined height. If the height is 100%,you have to wrap it inside an element with a defined height. For example:

<div style="height: 500px;"> <script src="http://demo.vaadin.com/xsembed/getEmbedJs" type="text/javascript"></script></div>

It is possible to restrict where the application can be embedded by using a whitelist. The add-onalso encrypts the client-server communication, which is more important for embedded applicationsthan usual.

You can get the Vaadin XS add-on from Vaadin Directory. It is provided as a Zip package.Download and extract the installation package to a local folder. Instructions for installation andfurther information is given in the README.html file in the package.

Some restrictions apply. You can have only one embedded application in one page. Also, somethird-party libraries may interfere with the communication. Other notes are given in the README.

11.3. Debug Mode and Window

Vaadin applications can be run in two modes: debug mode and production mode. The debugmode, which is on by default, enables a number of built-in debug features for Vaadin developers:

• Debug Window

• Display debug information in the Debug Window and server console

• On-the-fly compilation of Sass themes

11.3.1. Enabling the Debug Mode

The debug mode is enabled and production mode disabled by default in the UI templates createdwith the Eclipse plugin or the Maven archetypes. The debug mode can be enabled by giving aproductionMode=false parameter to the Vaadin servlet configuration:

@VaadinServletConfiguration( productionMode = false, ui = MyprojectUI.class)

Or with a context parameter in the web.xml deployment descriptor:

<context-param> <description>Vaadin production mode</description> <param-name>productionMode</param-name> <param-value>false</param-value></context-param>

Enabling the production mode disables the debug features, thereby preventing users from easilyinspecting the inner workings of the application from the browser.

Debug Mode and Window346

Advanced Web Application Topics

Page 349: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

11.3.2. Opening the Debug Window

Running an application in the debug mode enables the client-side Debug Window in the browser.You can open the Debug Window by adding "?debug" parameter to the URL of the UI, forexample, http://localhost:8080/myapp/?debug. The Debug Window has buttons forcontrolling the debugging features and a scrollable log of debug messages.

Figura 11.3. Debug Window

The functionalities are described in detail in the subsequent sections.You can move the windowby dragging it from the title bar and resize it from the corners. The Minimize button minimizesthe debug window in the corner of the browser window, and the Close button closes it.

If you use the Firebug plugin for Firefox or the Developer Tools console in Chrome, the logmessages will also be printed to the Firebug console. In such a case, you may want to enableclient-side debugging without showing the Debug Window with "?debug=quiet" in the URL. Inthe quiet debug mode, log messages will only be printed to the console of the browser debugger.

11.3.3. Debug Message Log

The debug message log displays client-side debug messages, with time counter in milliseconds.The control buttons allow you to clear the log, reset the timer, and lock scrolling.

347Opening the Debug Window

Advanced Web Application Topics

Page 350: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Figura 11.4. Debug Message Log

Logging to Debug Window

You can take advantage of the debug mode when developing client-side components, by usingthe standard Java Logger to write messages to the log. The messages will be written to thedebug window and Firebug console. No messages are written if the debug window is not openor if the application is running in production mode.

11.3.4. General Information

The General information about the application(s) tab displays various information about theUI, such as version numbers of the client and servlet engine, and the theme. If they do not match,you may need to compile the widget set or theme.

Figura 11.5. General Information

11.3.5. Inspecting Component Hierarchy

The Component Hierarchy tab has several sub-modes that allow debugging the componenttree in various ways.

General Information348

Advanced Web Application Topics

Page 351: Book of-vaadin-br Book of-vaadin-br Book of-vaadin-br

Connector Hierarchy Tree

The Show the connector hierarchy tree button displays the client-side connector hierarchy.As explained in Capítulo 16, Integrating with the Server-Side, client-side widgets are managedby connectors that handle communication with the server-side component counterparts. Theconnector hierarchy therefore corresponds with the server-side component tree, but the client-side widget tree and HTML DOM tree have more complexity.

Figura 11.6. Connector Hierarchy Tree

Clicking on a connector highlights the widget in the UI.

Inspecting a Component

The Select a component in the page to inspect it button lets you select a component in theUI by clicking it and display its client-side properties.

To view the HTML structure and CSS styles in more detail, you can use Firebug in Firefox, orthe Developer Tools in Chrome, as described in Secção 2.2.4, “Firefox e Firebug”. Firefox alsohas a built-in feature for inspecting HTML and CSS.

Analyzing Layout Problems

The Check layouts for potential problems button analyzes the currently visible UI and makesa report of possible layout related problems. All detected layout problems are displayed in thelog and also printed to the console.

349Inspecting Component Hierarchy

Advanced Web Application Topics