Difference between revisions of "Template:Tutorial common chapters"

From Documentation
(48 intermediate revisions by 4 users not shown)
Line 1: Line 1:
= Objectif du tutoriel =
+
= Tutorial Objective =
Notre application consiste simplement en un catalogue de voitures. Cette application a deux fonctions:
+
Our target application is a simple car catalog application. This application has two functions:
# Chercher des voitures.
+
# Search cars.
#: Entrez un mot-clé dans le champ d'entrée, cliquez <b>Search</b> et les résultats seront affichés dans la liste en dessous.
+
#: Enter a keyword in the input field, click <b>Search</b> and search results will be displayed in the car list below.
# Voir les détails.
+
# View details.
#: Cliquez sur un élément de la liste, la zone sous la liste de voiture affichera alors les détails de la voiture sélectionnée dont le modèle, le prix, une description et un aperçu.
+
#: Click an item from the car list, the area below the car list will show the selected car's details including model, price, description, and preview.
  
  
 
[[File:tutorial-searchexample.png| 400px | center]]
 
[[File:tutorial-searchexample.png| 400px | center]]
  
= Échauffement =
 
  
Cette section vous guide pour mettre en place un projet et utiliser ZK dans Eclipse. Si vous voulez d'abord savoir comment construire l'application avec ZK, démarrez d'abord depuis [[#Declaring Domain Class| Declaring Domain Class]]. Pour commencer, nous allons voir comment préparer un environnement pour construire une application web ZK à savoir configurer l'IDE, installer ZK et lancer l'application dans un serveur.
+
= Start from Example Project =
  
 +
You can get [https://github.com/zkoss-demo/gettingStarted/ the source code of this article] and import it to your IDE without starting from scratch. Please follow the README to run the project.
  
==Configurer Eclipse ==
+
If you want to start a new project, please refer to [[ZK Installation Guide/Quick Start]].
  
Dans ce tutoriel, Eclipse IDE 3.7 (indigo) pour Java EE developer [[File:Eclipse-javaee.png]] est utilisé pour montrer la construction de l'application 'catalogue de voitures'. ([http://www.eclipse.org/downloads/packages/release/indigo/sr2 Télécharger Eclipse] ici, extraire le fichier zip téléchargé dans un dossier et exécuter eclipse.exe pour lancer Eclipse.)
+
= Declaring Domain Class =
  
Pour pouvoir éditer les pages ZK UI dans Eclipse, ajoutez "zul" (nom des extensions des fichiers ZK UI) comme type de contenu de format XML en suivant les étapes suivantes:
+
The following is the domain object that represents a car.  
 
 
# Sélectionnez '''Window \ Preferences''' pour ouvrir la fenêtre Preferences
 
# À gauche, sélectionnez '''General --> Content Types'''. À droite, ouvrez le nœud ''Text''' dans la boîte "Content types" et sélectionnez '''XML'''
 
# Cliquez sur '''Add''' et ajoutez le type de contenu que vous souhaitez ajouter à savoir '''*.zul''' dans ce cas-ci, ensuite cliquez sur '''OK'''
 
 
 
[[File:Tutorial-add-contenttype.png| 400px | center]]
 
 
 
 
 
Une fois ceci terminé, Eclipse va utiliser l'éditeur XML pour ouvrir votre fichier zul.
 
 
 
== Installer ZK dans un Web Project==
 
 
 
'''Télécharger ZK'''
 
 
 
[http://www.zkoss.org/download/zk Téléchargez d'abord le ZK CE ] (le nom du fichier sera du genre ''zk-bin-[version].zip'') et extrayez le dans un dossier.
 
 
 
 
 
'''Créer un Project'''
 
 
 
Pour construire une application web, il faut d'abord créer un "Dynamic Web Project" dans Eclipse:
 
# Sélectionnez '''File \ New \ Dynamic Web Project'''
 
# Entrez '''tutorial''' comme nom du Project et laissez le reste par défaut.
 
 
 
[[File:Tutorial-newproject.png | 400px | center]]
 
 
 
* Vous pouvez laisser "Target runtime" à "none".
 
* Notez que l'on met la valeur de '''Dynamic web module version''' à 3.0 parce-que nous voulons utiliser Servlet 3.0 pour supprimer la configuration de l'application.
 
 
 
 
 
'''Installer ZK JAR'''
 
 
 
Pour utiliser ZK dans votre projet, vous devez copier les fichiers ZK JAR dans le dossier des librairies de votre projet.
 
 
 
Copiez les fichiers JAR depuis le répertoire suivant vers '''WebContent\WEB-INF\lib''':
 
* {YOUR_ZK_UNZIP_FOLDER}\dist\lib
 
* {YOUR_ZK_UNZIP_FOLDER}\dist\lib\ext
 
 
 
 
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
">
 
[[File:Icon_info.png ]]    Si vous préférez utiliser un serveur d'applications qui supporte '''des spécifications Servlet (< 3.0)''' plus anciennes ou '''JDK 1.5''', vous devez ajouter des configurations supplémentaires dans web.xml. Merci de vous référer au Guide d'Installation ZK. <ref> [[ZK Installation Guide/Quick Start/Create and Run Your First ZK Application Manually| ZK Installation Guide \ Create and Run Your First ZK Application Manually]] </ref>
 
</div>
 
 
 
 
 
'''Créer une page simple'''
 
 
 
Après l'installation, vous pouvez créer un zul simple pour vérifier que l'installation fonctionne correctement.
 
 
 
Dans Eclipse,
 
# Sélectionnez '''File \ New \ File''' (or '''File \ New \ Other \ File''' ) pour ajouter un nouveau fichier, '''hello.zul''', dans '''WebContent'''.
 
# Cliquez sur '''Source'''  pour modifier la source.
 
#: [[File:Tutorial-xmleditor.png| 400px | frame| center|c|creating a zul-file in eclipse's xml editor]]
 
# Copiez et collez l'extrait de code suivant dans hello.zul et enregistrez.
 
 
 
'''hello.zul'''
 
<source lang="xml">
 
<window title="My First ZK Application" border="normal">
 
Hello World!
 
</window>
 
</source>
 
 
 
 
 
 
 
 
 
Maintenant, dans la vue '''Project Explorer''', votre projet devrait ressembler à ceci:
 
 
 
[[File:Tutorial-project-structure.png | 200px | center]]
 
 
 
Si vous ne trouvez pas la vue '''Project Explorer''', sélectionnez le menu '''Window \ Show View \ Project Explorer''' pour l'ouvrir.
 
 
 
== Lancer une Application ==
 
<!--
 
將 new server 及 run on the server 分成兩個步驟,後面的章節可隨時依照run on the server的步驟執行範例程式
 
-->
 
 
 
 
 
Avant de lancer une application web, nous devons créer un serveur dans Eclipse. Sélectionnez '''Window \ Preferences''' pour ouvrir la fenêtre Preferences et sélectionnez '''Server \ Runtime Environments''' sur la gauche. Cliquez sur '''Add''' pour ajouter un environnement d'exécution de serveur.
 
 
 
[[File:Tutorial-preference-server.png | 400px | center]]
 
 
 
 
 
Sélectionnez '''Apache \ Tomcat v7.0 Server''' vu qu'il supporte Servlet 3.0 et cochez '''Create a new local server''', cliquez ensuite sur '''Next'''.
 
 
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
">
 
[[File:Icon_info.png ]]    Si vous utilisez JDK 1.5, vous pouvez utiliser Tomcat v6.0 mais il faudra faire davantage de configurations dans web.xml. Merci de voir le ZK Installation Guide dans [[#References| References]] .
 
</div>
 
 
 
[[File:Tutorial-newserver.png | 400px | center]]
 
 
 
 
 
 
 
Si vous avez précédemment installé Tomcat 7, fournissez simplement le chemin du répertoire. Si vous ne l'avez pas, suivez les étapes suivantes:
 
# Cliquez sur '''Download and Install''' et choisissez un répertoire.
 
#: '''Notez que le chemin d'installation ne peut contenir aucun caractère non-ASCII.'''
 
#: [[File:Tutorial-downloadinstall.png | 400px | center]]
 
# Acceptez la licence et attendez.
 
#: '''Eclipse affichera un message d'erreur avant que l'installation ne s'achève, ignorez le.'''
 
#: [[File:Tutorial-installing-unknown.png | 400px | center]]
 
#: '''Patientez et n'interrompez pas l'installation pour être certain qu'elle s'effectue correctement.'''
 
#: [[File:Tutorial-installing-progress.png | center]]
 
#: Eclipse va télécharger et installer Tomcat dans le dossier que vous avez spécifié. 
 
# Lordque l'installation est finie, cliquez sur '''Finish'''
 
 
 
 
 
Vous devriez maintenant voir une nouvelle entrée dans '''Server runtime environments'''.
 
 
 
[[File:Tutorial-server-complete.png | 500px | center]]
 
 
 
 
 
 
 
Faites un clique droit sur hello.zul et sélectionnez '''Run As \ Run on Server''' pour faire tourner ce zul sur un serveur d'applications.
 
 
 
[[File:Tutorial-runonserver.png | 500px | center]]
 
 
 
 
 
 
 
Choisissez un Tomcat 7. Vous pouvez aussi cocher l'option '''Always use this server when running this project''' pour ne pas devoir choisir un serveur à chaque fois que vous lancerai l'application par la suite. Cliquez sur '''Finish''' et attendez que le serveur démarre.
 
 
 
[[File:Tutorial-choose-server.png | 400px | center]]
 
 
 
 
 
 
 
Une fois le serveur démarré, Eclipse va ouvrir un browser et vous connecter automatiquement à http://localhost:8080/tutorial/hello.zul . Si vous voyez l'image suivante, alors votre projet est prêt pour utiliser ZK.
 
 
 
[[File:Tutorial-hello.png | 400px | center]]
 
 
 
Vous pouvez revenir ici et suivre à nouveau ces étapes pour lancer votre application au cours de ce tutoriel
 
 
 
== Importer et lancer l'Application exemple ==
 
 
 
Nous avons préparé un ficher zip projet Eclipse qui contient le code source complet, vous pouvez le télécharger et l'importer dans votre Eclipse sans avoir à démarrer tout de 0.
 
 
 
Pour utiliser l'application exemple, suivez les étapes suivantes:
 
# [http://sourceforge.net/projects/zkbook/files/GettingStarted/getzkup-20131127.zip/download Téléchargez le fichier zip du projet].
 
# Dans Eclipse, sélectionnez '''File \ Import \ General \ Existing Projects into Workspace''', choisissez '''Select archive file''' pour importer le zip de l'application comme  projet dans Eclipse.
 
# Suivez ensuite les instructions de [[#Run an Application |Run an Application]] pour lancer l'application.
 
 
 
<!--
 
Nous décrivons les objets domaine ici pcq cette section est indépendante des sections MVC et MVVM et la partie domaine est identique pour ces 2 design patterns.
 
-->
 
 
 
= Déclaration des classes du domaine =
 
 
 
Ce qui suit est l'objet du domaine qui représente une voiture.  
 
  
 
<source lang="java">
 
<source lang="java">
Line 177: Line 32:
 
}
 
}
 
</source>
 
</source>
* Merci de vous référer à la section References pour voir le code complet. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/Car.java Car.java] </ref>
 
  
On définit ensuite une classe de service pour effectuer la logique business (chercher des voitures) tel que montré ci-dessous:
+
We then define a service class to perform the business logic (search cars) shown below:
  
 
<source lang="java">
 
<source lang="java">
Line 193: Line 47:
 
* search cars according to keyword in  model and make.
 
* search cars according to keyword in  model and make.
 
* @param keyword for search
 
* @param keyword for search
* @return list of car that match the keyword
+
* @return list of car that matches the keyword
 
*/
 
*/
 
public List<Car> search(String keyword);
 
public List<Car> search(String keyword);
Line 199: Line 53:
 
</source>
 
</source>
  
Dans cet exemple, nous avons défini une classe - <tt>CarServeImpl</tt> qui implémente l'interface ci-dessus. Par soucis de simplicité, elle utilise une liste objet statique comme modèle de données. Vous pouvez la réécrire de sorte qu'elle se connecte à une base de données dans une application réelle. Les détails de l'implémentation ne sont pas l'objet de cet article, merci de vous référer à la section References.<ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarService.java CarService.java] [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarServiceImpl.java CarServiceImpl.java] </ref>
+
In this example, we have defined a class, <code>CarServeImpl</code>, that implements the above interface. For simplicity, it uses a static list object as the data model. You can rewrite it so that it connects to a database in a real application. Its implementation details are not in the scope of this article, please refer to source code repository.
  
=Construire l'interface utilisateur =
+
=Building User Interface =
  
Le design de l'UI est un bon début pour construire une application vu qu'il vous aide à définir l'étendue de votre application. ZK fournit des centaines de composants UI prêts à l'emploi de sorte que les développeurs peuvent rapidement construire l'interface utilisateur de leur choix en combinant et en mélangeant ces composants sans avoir à les créer.  
+
UI is a good start to building an application as it helps you define the scope of your application. ZK provides hundreds of readily made UI components, so developers can rapidly build their desired user interface by combining and mix-matching these components without having to create a page from scratch.  
  
Dans ZK, vous pouvez utiliser ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, un langage formaté XML, pour décrire les UI. Suivant la convention ZK, les fichiers décrivant les UI avec ZUML utilisent comme suffixe '''.zul'''. Dans les fichiers zul, un composant peut être représenté comme un élément XML (tag) et vous pouvez configurer pour chaque composant son style, son comportement et sa fonction via les attributs XML de cet élément.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>
+
In ZK, you can use [[ZUML Reference|ZK User Interface Markup Language (ZUML)]], an XML-formatted language, to describe UI. By ZK's convention, the files to describe the user interface with ZUML uses '''.zul''' as the name suffix. In zul files, one component is represented as an XML element (tag) and you can configure each component's style, behavior, and function by setting XML element's attributes. (check [[ZK Component Reference|ZK Component Reference]] for details)
  
Dans cet exemple, nous voulons d'abord concevoir une fenêtre avec un titre spécifique et un bord normal qui sera la fenêtre de notre application.
+
In this example application, first of all, we want to use a <code>Window</code> with the specified title and normal border as our application's frame.
  
  
'''Extrait de search.zul'''
+
As <code>Window</code> is the outermost component, it is called the ''root component''. <code>Window</code> is a commonly used container because it makes your web application look like a desktop application. Besides, it can also enclose other components. All other components inside <code>Window</code> are called its ''child components'' and should be put in <code><window></code>'s body.
<source lang="xml">
 
  
<window title="Search" width="600px" border="normal">
+
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
<window title="Search" border="normal"
 +
width="600px">
 
<!-- put child components inside a tag's body -->
 
<!-- put child components inside a tag's body -->
 
</window>
 
</window>
</source>
+
</syntaxhighlight>
 +
 
 +
* Line 1: Specifying title bar text with <code>title</code> and make <code><window></code> display a normal border with <code>border</code> . For <code>width</code> attribute, use CSS like syntax such as <code>800px</code> or <code>60%</code>.
  
Vu que ''window'' et le composant 'englobant' principal, il est appelé ''root component''. ''Window'' est un container souvent utilisé parce-que c'est un élément d'affichage de base d'une application de type bureau et qui peut en même temps contenir d'autres composants. Tous les autres composants inclus dans ''window'' sont appelés ''child components'' et doivent être placés dans le body de la fenêtre. Nous mettons un texte dans la barre de titre de ''window''' grâce à l'attribut "title" et nous faisons en sorte que ''window'' s'affiche avec un bord normal grâce à l'attribut "border". Pour l'attribut "width", utilisez une syntaxe de type CSS comme "800px" ou "60%".
 
  
 +
Basically, our example application's user interface is divided into 3 areas within the <code><window></code> (from top to bottom):
  
De base, l'UI de notre application est divisée en 3 zones à l'intérieur de ''window'' qui sont, de haut en bas, la fonction de recherche, la liste des voitures et les détails de la voiture.
+
# search function
 +
# car list
 +
# car details.
  
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
  
  
'''Search Area:'''
+
== Search Area ==
ZK components are like building blocks, you can combine and mix match existing components to construct your desired UI. To allow users to search, we need a text to prompt users for input, a place to enter keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:
+
ZK components are like building blocks, you can combine and mix-match existing components to construct your desired UI. To allow users to search, we need a text to prompt users for input, a place to enter keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
  
<hbox align="center">
+
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
Keyword:
+
<syntaxhighlight lang="XML" line>
<textbox id="keywordBox" />
+
Keyword:
<button id="searchButton" label="Search" image="/img/search.png" />
+
<textbox id="keywordBox" />
</hbox>
+
<button id="searchButton" label="Search" iconSclass="z-icon-search" style="margin: 0 0 5px 5px"/>
 +
</syntaxhighlight>
  
</source>
+
* Line 1~2: Specifying the <code>id</code> attribute for some components allows you to control them by referencing their ''id''.
 +
* Line 3: You can use built-in Font Awesome icon at <code>iconSclass</code>. Please refer to [[ZK_Component_Reference/Base_Components/LabelImageElement#IconSclass| LabelImageElement#IconSclass]] for details.
  
<tt>hbox</tt> is a layout component that arranges its child components horizontally and you can probably guess by now that the '''h''' represents ''horizontal''. As these child components have different heights, we set the "align" attribute to "center" so they are aligned neatly along their center line. Here we also specify an "id" attribute for some components which allows you to control them by referencing their ''id''. You can also easily create an image button by specifying the path for the "image" attribute.  
+
== Car List Area ==
 +
ZK provides several components to display a collection of data such as <code>listbox</code>, <code>grid</code>, and <code>tree</code>. In this example, we use a <code>listbox</code> to display a list of cars with 3 columns: Model, Make, and Price. Here we use <code>listcell</code> with static label to demonstrate structure of a <code>listitem</code>. Later, we'll talk about how to create <code>listitem</code> dynamically with a collection of data.
  
 +
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
<listbox id="carListbox" emptyMessage="No car found in the result" rows="5">
 +
    <listhead>
 +
        <listheader label="Model" />
 +
        <listheader label="Make" />
 +
        <listheader label="Price" width="20%"/>
 +
    </listhead>
 +
    <listitem>
 +
        <listcell label="car model"></listcell>
 +
        <listcell label="make"></listcell>
 +
        <listcell>$<label value="price" /></listcell>
 +
    </listitem>
 +
</listbox>
 +
</syntaxhighlight>
 +
* Line 1: <code>rows</code> determines the max visible row. <code>emptyMessage</code> is used to show a message when <code>listbox</code> contains no items.
 +
* Line 2: The <code>listbox</code>  is a container component, and you can add <code>listhead</code> to define a column.
 +
* Line 7: The <code>listitem</code> is used to display data, and the number of <code>listcell</code> in one <code>listitem</code> usually equals to the number of <code>listheader</code>.
  
'''Car List Area.''' ZK provides several components to display a collection of data such as ''listbox'', ''grid'', and ''tree''. In this example, we have chosen to use a ''listbox'' to display a list of cars with 3 columns: Model, Make and Price. We set the "height" attribute so the number of rows visible is limited with respect to the height specified; you can drag scroll-bar to see the rest of rows. The "emptyMessage" attribute is used to show a message when ''listbox'' contains no items. The ''listbox'' is a container component, and you can add ''listhead'' to define a column. The ''listitem'' is used to display data, and the number of ''listcell'' in one ''listitem'' should equal to the number of ''listheader''. Here we use ''listcell'' with static label to demonstrate structure of a ''listitem'', and we'll talk about how to create ''listitem'' dynamically with respect to each data object in the next chapter.
+
== Car Details Area ==
 
+
<code>hlayout</code> and <code>vlayout</code> are layout components which arrange their child components in horizontal and vertical order.  
'''Extracted from search.zul'''
 
<source lang="xml">
 
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
 
<listhead>
 
<listheader label="Model" />
 
<listheader label="Make" />
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
<listitem>
 
<listcell label="car model"></listcell>
 
<listcell label="make"></listcell>
 
<listcell>$<label value="price" /></listcell>
 
</listitem>
 
</listbox>
 
</source>
 
 
 
 
 
'''Car Details Area.''' Like the ''hbox'', ''vbox'' is also a layout component which arranges its child component in vertical order. By combing these 2 layout components, we can present more information on a screen.  The "style" attribute allows you to customize component's style with CSS syntax.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<image id="previewImage" width="250px" />
 
<vbox>
 
<label id="modelLabel" />
 
<label id="makeLabel" />
 
<label id="priceLabel" />
 
<label id="descriptionLabel"/>
 
</vbox>
 
</hbox>
 
</source>
 
 
 
  
You can see the complete zul file through the link in the References section. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/WebContent/search.zul search.zul] </ref>
+
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
<hlayout style="margin-top:20px" width="100%">
 +
<image id="previewImage" width="250px" />
 +
<vlayout hflex="1">
 +
<label id="modelLabel" />
 +
<label id="makeLabel" />
 +
<label id="priceLabel" />
 +
<label id="descriptionLabel" />
 +
</vlayout>
 +
</hlayout>
 +
</syntaxhighlight>
 +
* Line 1: the <code>style</code> attribute allows you to customize component's style with CSS syntax.

Revision as of 02:24, 19 January 2022

Tutorial Objective

Our target application is a simple car catalog application. This application has two functions:

  1. Search cars.
    Enter a keyword in the input field, click Search and search results will be displayed in the car list below.
  2. View details.
    Click an item from the car list, the area below the car list will show the selected car's details including model, price, description, and preview.


Tutorial-searchexample.png


Start from Example Project

You can get the source code of this article and import it to your IDE without starting from scratch. Please follow the README to run the project.

If you want to start a new project, please refer to ZK Installation Guide/Quick Start.

Declaring Domain Class

The following is the domain object that represents a car.

public class Car {
	private Integer id;
	private String model;
	private String make;
	private String preview;
	private String description;
	private Integer price;
	//omit getter and setter for brevity
}

We then define a service class to perform the business logic (search cars) shown below:

public interface CarService {

	/**
	 * Retrieve all cars in the catalog.
	 * @return all cars
	 */
	public List<Car> findAll();
	
	/**
	 * search cars according to keyword in  model and make.
	 * @param keyword for search
	 * @return list of car that matches the keyword
	 */
	public List<Car> search(String keyword);
}

In this example, we have defined a class, CarServeImpl, that implements the above interface. For simplicity, it uses a static list object as the data model. You can rewrite it so that it connects to a database in a real application. Its implementation details are not in the scope of this article, please refer to source code repository.

Building User Interface

UI is a good start to building an application as it helps you define the scope of your application. ZK provides hundreds of readily made UI components, so developers can rapidly build their desired user interface by combining and mix-matching these components without having to create a page from scratch.

In ZK, you can use ZK User Interface Markup Language (ZUML), an XML-formatted language, to describe UI. By ZK's convention, the files to describe the user interface with ZUML uses .zul as the name suffix. In zul files, one component is represented as an XML element (tag) and you can configure each component's style, behavior, and function by setting XML element's attributes. (check ZK Component Reference for details)

In this example application, first of all, we want to use a Window with the specified title and normal border as our application's frame.


As Window is the outermost component, it is called the root component. Window is a commonly used container because it makes your web application look like a desktop application. Besides, it can also enclose other components. All other components inside Window are called its child components and should be put in <window>'s body.

Extracted from search.zul

1 	<window title="Search" border="normal"
2 	width="600px">
3 		<!-- put child components inside a tag's body -->
4 	</window>
  • Line 1: Specifying title bar text with title and make <window> display a normal border with border . For width attribute, use CSS like syntax such as 800px or 60%.


Basically, our example application's user interface is divided into 3 areas within the <window> (from top to bottom):

  1. search function
  2. car list
  3. car details.
Tutorial-ui-3areas.png


Search Area

ZK components are like building blocks, you can combine and mix-match existing components to construct your desired UI. To allow users to search, we need a text to prompt users for input, a place to enter keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:

Extracted from search.zul

1 Keyword:
2 <textbox id="keywordBox" />
3 <button id="searchButton" label="Search" iconSclass="z-icon-search" style="margin: 0 0 5px 5px"/>
  • Line 1~2: Specifying the id attribute for some components allows you to control them by referencing their id.
  • Line 3: You can use built-in Font Awesome icon at iconSclass. Please refer to LabelImageElement#IconSclass for details.

Car List Area

ZK provides several components to display a collection of data such as listbox, grid, and tree. In this example, we use a listbox to display a list of cars with 3 columns: Model, Make, and Price. Here we use listcell with static label to demonstrate structure of a listitem. Later, we'll talk about how to create listitem dynamically with a collection of data.

Extracted from search.zul

 1 <listbox id="carListbox" emptyMessage="No car found in the result" rows="5">
 2     <listhead>
 3         <listheader label="Model" />
 4         <listheader label="Make" />
 5         <listheader label="Price" width="20%"/>
 6     </listhead>
 7     <listitem>
 8         <listcell label="car model"></listcell>
 9         <listcell label="make"></listcell>
10         <listcell>$<label value="price" /></listcell>
11     </listitem>
12 </listbox>
  • Line 1: rows determines the max visible row. emptyMessage is used to show a message when listbox contains no items.
  • Line 2: The listbox is a container component, and you can add listhead to define a column.
  • Line 7: The listitem is used to display data, and the number of listcell in one listitem usually equals to the number of listheader.

Car Details Area

hlayout and vlayout are layout components which arrange their child components in horizontal and vertical order.

Extracted from search.zul

1 	<hlayout style="margin-top:20px" width="100%">
2 		<image id="previewImage" width="250px" />
3 		<vlayout hflex="1">
4 			<label id="modelLabel" />
5 			<label id="makeLabel" />
6 			<label id="priceLabel" />
7 			<label id="descriptionLabel" />
8 		</vlayout>
9 	</hlayout>
  • Line 1: the style attribute allows you to customize component's style with CSS syntax.