Learn ZK in 10 Minutes fr"

From Documentation
Line 82: Line 82:
  
  
Pour contrôler l'UI, il faut d'abord implémenter une classe contrôleur qui hérite de ZK's '''SelectorComposer'''<ref> SelectorComposer was introduced in ZK 6.0</ref> for a ZUL. Then, you can retrieve the UI component's Java object by annotating '''@Wire''' on controller's member variables. After this has been done, you can then control and manipulate UI by accessing those annotated member variables.  
+
Pour contrôler l'UI, il faut d'abord implémenter une classe contrôleur qui hérite de ZK's '''SelectorComposer'''<ref> SelectorComposer was introduced in ZK 6.0</ref> pour un ZUL. Ensuite, vous pouvez récupérer l'objet Java du composant UI en annotant '''@Wire''' sur les variables membres du contrôleur. Il devient alors possible de contrôler et manipuler l'UI en accédant à ces variables annotées.  
  
  

Revision as of 06:19, 5 March 2014

Qu'est-ce que ZK ?

ZK est un UI framework qui vous permet de construire des pages web et des applications mobiles sans avoir à apprendre JavaScript ou AJAX.

Composition rapide avec l'UI

Construire des Interfaces Utilisateurs (UI) est facile avec ZK; il suffit de les assembler et les organiser en utilisant des centaines de composants qui se trouvent à portée de main. Vous pouvez rapidement construire votre propre interface utilisateur à partir de différents composants ZK. Le style, le comportement et la fonction de chaque composant peuvent être ajustés selon vos désirs.


Getstarted-simpleZK-UI.png


ZUL, un langage formaté XML et facile à lire, est utilisé pour décrire la fenêtre d'enregistrement ci-dessus.


	<window border="normal" width="400px" title="Welcome! New User">
		<grid hflex="1"> <!-- hflex="1" - available width inside parent (window) -->
			<auxhead>
				<auxheader colspan="2" label="Registration Form" style="font-size:16px" image="../images/picture.png"/>
			</auxhead>
	 		<columns visible="false">
	 			<column></column>
	 			<column></column>
	 		</columns>
			<rows>
				<row>
					User Name <textbox id="nameBox" hflex="1" constraint="no empty"/>
				</row>
				<row>
					Gender:
					<radiogroup id="genderRadio">
						<radio label="Male" value="male" image="/images/male.png" checked="true"/>
						<radio label="Female" value="female" image="/images/female.png"/>
					</radiogroup>
				</row>
				<row >
					Birthday <datebox id="birthdayBox" hflex="1" constraint="no empty, no today, no future"/>
				</row>
				<row spans="2" align="center" >
					<hlayout>
						<checkbox id="acceptTermBox"/> Accept Term of Use
					</hlayout>
				</row>
				<row spans="2" align="right">
					<hlayout>
						<button id="resetButton" label="Reset" />
						<button id="submitButton" label="Submit" disabled="true"/>
					</hlayout>
				</row>
			</rows>
		</grid>
	</window>
  • Ligne 1: Un tag représente un compsant. Certains composants sont capables de contenir, à l'intérieur d'eux-même, des composants enfants . Dans cet exemple, une window contient une grid.
  • Ligne 32: Vous pouvez donner un attribut "id" à un composant de sorte à pouvoir le contrôler depuis le "UI controller".


ZK vous permet aussi de construire des UI par programmation comme lorsque vous utilisez Java Swing dans un Richlet [8] .

Les composants UI ZK sont semblables à des blocs à construire; vous pouvez les combiner, les mélanger, les faire hériter d'autres composants et fabriquer un nouveau composant qui répond à vos besoins. Cette polyvalence accroît la possibilité de réutilisation ainsi que la modularité [9] .


Contrôle de l'UI intuitif

ZK est un framework basé sur les composants avec un modèle de programmation événementiel, et donc les développeurs ajoutent des fonctions qui répondent aux événements déclenchés sur les composants par l'utilisateur.


Contrôleur d'UI

Pour contrôler l'UI, il faut d'abord implémenter une classe contrôleur qui hérite de ZK's SelectorComposer[1] pour un ZUL. Ensuite, vous pouvez récupérer l'objet Java du composant UI en annotant @Wire sur les variables membres du contrôleur. Il devient alors possible de contrôler et manipuler l'UI en accédant à ces variables annotées.


package foo;

// some import statements are omitted for brevity.

public class RegistrationComposer extends SelectorComposer<Component> {

	@Wire
	private Button submitButton;	

	@Wire
	private Checkbox acceptTermBox;
}
  • line 7,10: Variable names "submitButton" and "acceptTermBox" corresponds to components' id attributes which are specified at mentioned ZUL in the previous section.


We can then use the controller above to control our UI components by specifying attribute "apply" in the ZUL.

	<window border="normal" width="400px" title="Welcome! New User"
	apply="foo.RegistrationComposer">
	<!-- omit other components for brevity -->
	</window>
  • Line 2: By applying the controller to the root component, you can control all child components inside the root component.

Notes

  1. SelectorComposer was introduced in ZK 6.0

Handle User Action

One of the features of the registration form application above is that the "Submit button" is only enabled (clickable) when a user checks the "Term of use" checkbox.

First, "Submit" button is disabled when "Accept Term" checkbox remains unchecked.

File:Simplezk-uncheck.png


When "Accept Term" checkbox is checked, "Submit" button is enabled with a checked icon.


File:Simplezk-check.png


As ZK is an event-driven framework, user action is therefore handled by listening to component's events. ZK provides an annotation @Listen which can be used on a method to listen a component's event you specify. To achieve the above feature, you could annotate a method to listen to an "onCheck" event of "Accept Term of Use" checkbox. Whenever a user checks/unchecks the checkbox to trigger the "onCheck" event, ZK invokes the annotated method. We implement the above UI effect by changing properties of a component (Java object) in the annotated method.


import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;

public class RegistrationComposer extends SelectorComposer<Component> {
	@Wire
	private Button submitButton;
	@Wire
	private Checkbox acceptTermBox;

	@Listen("onCheck = #acceptTermBox")
	public void changeSubmitStatus(){
		if (acceptTermBox.isChecked()){
			submitButton.setDisabled(false);
			submitButton.setImage("/images/submit.png");
		}else{
			submitButton.setDisabled(true);
			submitButton.setImage("");
		}
	}

}
  • line 14: Use @Listen to declare a method to handle the onCheck event of "acceptTermBox".
  • line 17,18: Enable "Submit" button and display a checked icon when "Accept Term of Use" checkbox is checked.
  • line 20,21: Disable "Submit" button and clear the checked icon.


With ZK's help, you can easily add fancy UI effects such as tooltip, drag & drop, and hot key, etc. [8] to your application.


Easy Backend Integration

As ZK allows you to control UI via a controller at the server-side, the controller is therefore the main extension point to integrate any Java library or framework. To integrate ZK with other frameworks, write your controller code to use classes of back-end systems that construct your business or persistence layer.

Integrate Third-Party Library

With the help of ZK's UI controller - SelectorComposer, it is easy to integrate your legacy system service class, domain object, and any third party library such as Log4j.


public class RegistrationIntegrateComposer extends SelectorComposer<Component> {

	//omit other variables for brevity
	private static Logger logger = Logger.getLogger(RegistrationIntegrateComposer.class.getName());
	private LegacyRegister legacyRegister = new LegacyRegister();
	private User newUser = new User();

	@Listen("onClick = #submitButton")
	public void register(){
		//save user input into newUser object
		legacyRegister.add(newUser);
		logger.debug("a user was added.");
		//...
	}
}
  • Line 4,12: Call Log4j to log error.
  • Line 5,11: Use your legacy system object in the controller.
  • Line 6,11: Use your own domain object.

Integrate Business and Persistence Layer Framework

It is very important that a UI framework can cooperate with other business or persistence layer frameworks when building a multi-tier web application. ZK is easily integratable with business layer frameworks like Spring.


Assume you have implemented some classes according to Data Access Object (DAO) pattern as your application's persistence layer with Hibernate, JPA or other persistence framework. It is in your controller that you should use these classes to implement your application's feature.


@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class RegistrationSpringComposer extends SelectorComposer<Component> {

	@WireVariable
	private RegistrationDao registrationDao;

	@Listen("onClick = #submitButton")
	public void submit(){
		// omit irrelevant code for brevity
		registrationDao.add(newUser);
	}
}
  • Line 1: To use CDI, simply use another resolver: org.zkoss.zkplus.cdi.DelegatingVariableResolver.class .
  • Line 4: For those variables with @WireVariable , ZK will inject qualified Spring beans by retrieving them from Spring context with variable resolver.

References

  1. Check out demonstrations of our components: ZK Demo
  2. Try ZK now!: Download ZK
  3. Learn ZK MVC by example: Get ZK Up and Running with MVC
  4. Learn ZK MVVM by example: Get ZK Up and Running with MVVM
  5. Learn basic concepts in more detail: Read "ZK Essential"
  6. Dive into all aspects of ZK: Read "ZK Developer's Reference"
  7. Use our tool to help make your development more productive: Read "ZK Studio Essentials"
  8. Build UI programmatically: Richlet
  9. Extend existing components: Macro Component
  10. Improve user experience: UI Pattern