-
FEATURED COMPONENTS
First time here? Check out the FAQ!
Hi,
many of the examples are in the following form:
<zk> <zscript> // some data is initialized, say a listmodel </zscript> <listbox model="@{model}"...> </listbox> </zk>
My question would be what is the equivalent of the zscripts here in a Java approach? I looked into composers, use and apply attributes, but could not make to code work, which works with the zscript...
thanks a lot
Which is your code in Java ?
You can set the model for a listbox using : yourListbox.setModel(your_listmodel)...
Thanks for the reply! This will be easy I think. What I tried to do, is to create a page variable from Java code (instead of zscript code). Like in this simple example:
<zk> <zscript> String[] data = new String[30]; for(int j=0; j < data.length; ++j) { data = "option "+j; } ListModel strset = new SimpleListModel(data); </zscript> <combobox id="list" width="200px" model="${strset}"/> </zk>
Here the "strset" is a page variable. I was trying to achieve what the zscript code does, just from Java. Now I see two approaches (at least :))
1. Create an init class which extends the AnnotateDataBinderInit, and bind some object like
page.setVariable("person", person);
thanks again
Yes, this is a better approach.
Please check http://docs.zkoss.org/wiki/Data_binding
@zedkey
Hi zedkey, i can post code for looking how this is done in my sample application.
I hope it's well documented.
Stephan
branch.zul
<?xml version="1.0" encoding="UTF-8" ?> <zk xmlns="http://www.zkoss.org/2005/zul" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd"> <window id="branchListWindow" title="Branches" use="org.myfirm.module.branch.BranchListCtrl" border="none" width="100%"> <toolbar> <toolbarbutton id="btnNewBranch" image="/images/icons/page_detail.gif" tooltiptext="Create new branch" /> <toolbarbutton id="btnFindBranchDialog" image="/images/icons/find.gif" tooltiptext="Find/Filter branches" /> </toolbar> <listbox id="listBoxBranch" width="100%" height="100%" pagingPosition="top" mold="paging" pageSize="20" multiple="false"> <listhead sizable="true"> <listheader label="Branch description" sort="auto" width="25%" /> <listheader label="No." sort="auto" width="20%" /> <listheader label="Edit" sort="auto" width="10%" /> </listhead> </listbox> </window> </zk>
branchListCtrl.java
/* * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * This is the controller class for the brancheList.zul file. * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * it extends from our BaseCtrl class. * * * */ package org.myfirm.module.branch; import java.util.HashMap; import org.apache.log4j.Logger; import org.myfirm.module.branch.model.BranchComparator; import org.myfirm.module.branch.model.BranchListModelItemRenderer; import org.myfirm.util.BaseCtrl; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zkplus.spring.SpringUtil; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listheader; import org.zkoss.zul.Listitem; import org.zkoss.zul.Window; import de.daibutsu.backend.model.Branche; import de.daibutsu.backend.service.BrancheService; public class BranchListCtrl extends BaseCtrl { private static Logger logger = Logger.getLogger(BranchListCtrl.class); private static final long serialVersionUID = 2038742641853727975L; private Window branchListWindow; // autowire the window-id from zul file private Listbox listBoxBranch; private BrancheService brancheService; private void setBrancheService(BrancheService brancheService) { this.brancheService = brancheService; } public BrancheService getBrancheService() { if (brancheService == null) { brancheService = (BrancheService) SpringUtil.getBean("brancheService"); setBrancheService(brancheService); } return brancheService; } public BranchListCtrl() { super(); if (logger.isInfoEnabled()) { logger.info("--> "); } } public void onCreate$branchListWindow(Event event) throws Exception { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doOnCreateCommon(branchListWindow); // Set the ListModel and the itemRenderer. The ZKoss ListmodelList do in // most times satisfy your needs listBoxBranch.setModel(new ListModelList(getBrancheService().getAlleBranche())); // Assign the Comparator for allow sorting Listheader lh_Branch_No = (Listheader) event.getTarget().getFellow("lh_Branch_No"); lh_Branch_No.setSortAscending(new BranchComparator(true, BranchComparator.FieldsEnum.BRANCH_NR)); lh_Branch_No.setSortDescending(new BranchComparator(false, BranchComparator.FieldsEnum.BRANCH_NR)); Listheader lh_Branch_Descr = (Listheader) event.getTarget().getFellow("lh_Branch_Descr"); lh_Branch_Descr.setSortAscending(new BranchComparator(true, BranchComparator.FieldsEnum.BRANCH_DESCRIPTION)); lh_Branch_Descr.setSortDescending(new BranchComparator(false, BranchComparator.FieldsEnum.BRANCH_DESCRIPTION)); listBoxBranch.setItemRenderer(new BranchListModelItemRenderer()); } @SuppressWarnings("unchecked") public void onDoubleClicked(Event event) throws Exception { // get the selected object Listitem item = listBoxBranch.getSelectedItem(); if (item != null) { // store the selected customer object Branche branche = (Branche) item.getAttribute("data"); if (logger.isInfoEnabled()) { logger.info("--> " + branche.getBraBezeichnung()); } /* * We can call our Dialog zul-file with parameters. So we can call * them with a object of the selected item. For handed over these * parameter only a Map is accepted. So we put the object in a * HashMap. */ HashMap map = new HashMap(); map.put("branche", branche); /* * we can additionally handed over the listBox, so we have in the * dialog access to the listbox Listmodel. This is fine for * syncronizing the data in the customerListbox from the dialog when * we do a delete, edit or insert a customer. */ map.put("lbBranch", listBoxBranch); map.put("branchCtrl", this); // call the zul-file with the parameters packed in a map Executions.createComponents("/WEB-INF/pages/branch/branchDialog.zul", null, map); } } /* * call the branche dialog */ @SuppressWarnings("unchecked") public void onClick$btnNewBranch(Event event) throws Exception { if (logger.isDebugEnabled()) { logger.debug("--> " + event.toString()); } // create a new branch object Branche branche = getBrancheService().getNewBranche(); /* * We can call our Dialog zul-file with parameters. So we can call them * with a object of the selected item. For handed over these parameter * only a Map is accepted. So we put the object in a HashMap. */ HashMap map = new HashMap(); map.put("branche", branche); /* * we can additionally handed over the listBox, so we have in the dialog * access to the listbox Listmodel. This is fine for syncronizing the * data in the customerListbox from the dialog when we do a delete, edit * or insert a customer. */ map.put("lbBranch", listBoxBranch); map.put("branchCtrl", this); // call the zul-file with the parameters packed in a map Executions.createComponents("/WEB-INF/pages/branch/branchDialog.zul", null, map); } }
The Comparator for allow sorting in the list.
BranchComparator.java
package org.myfirm.module.branch.model; import java.io.Serializable; import java.util.Comparator; import de.daibutsu.backend.model.Branche; public class BranchComparator implements Comparator<Branche>, Serializable { private static final long serialVersionUID = -3801900439306479543L; public enum FieldsEnum { BRANCH_NR, // branch no. BRANCH_DESCRIPTION, // branch name } private boolean ascending; final private FieldsEnum columnIndex; public BranchComparator(boolean ascd, FieldsEnum columnIndex) { this.ascending = ascd; this.columnIndex = columnIndex; assert columnIndex != null; } @Override public int compare(Branche o1, Branche o2) { final int v; switch (columnIndex) { case BRANCH_NR: // v = NumberUtils.compare(k1.getKunId(), k2.getKunId()); v = o1.getBraNr().compareTo(o2.getBraNr()); break; case BRANCH_DESCRIPTION: v = o1.getBraBezeichnung().compareTo(o2.getBraBezeichnung()); break; // In the case of unknown default: throw new IllegalArgumentException(); } return ascending ? v : -v; } }
The Itemrenderer
BranchListModelItemRenderer.java
package org.myfirm.module.branch.model; import org.apache.log4j.Logger; import org.zkoss.zk.ui.sys.ComponentsCtrl; import org.zkoss.zul.Image; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listitem; import org.zkoss.zul.ListitemRenderer; import de.daibutsu.backend.model.Branche; public class BranchListModelItemRenderer implements ListitemRenderer { private static Logger logger = Logger.getLogger(BranchListModelItemRenderer.class); @Override public void render(Listitem item, Object data) throws Exception { Branche branche = (Branche) data; if (logger.isInfoEnabled()) { logger.info("--> " + branche.getBraNr() + "|" + branche.getBraBezeichnung()); } Listcell lc = new Listcell(branche.getBraBezeichnung()); lc.setParent(item); lc = new Listcell(branche.getBraNr()); lc.setParent(item); lc = new Listcell(); Image img = new Image(); img.setSrc("/images/icons/page_detail.gif"); lc.appendChild(img); lc.setParent(item); item.setAttribute("data", data); // ComponentsCtrl.applyForward(img, "onClick=onImageClicked"); // ComponentsCtrl.applyForward(item, "onClick=onClicked"); ComponentsCtrl.applyForward(item, "onDoubleClick=onDoubleClicked"); } }
baseCtrl.java
*/ * thanks to hne */ package org.myfirm.util; import java.util.List; import java.util.Map; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Components; import org.zkoss.zk.ui.event.CreateEvent; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zkplus.databind.AnnotateDataBinder; import org.zkoss.zul.Window; public abstract class BaseCtrl extends Window implements AfterCompose { private static final long serialVersionUID = -2179229704315045689L; protected AnnotateDataBinder binder; // protected Workspace ws; protected Map<String, Object> args; public void doOnCreateCommon(Window w) throws Exception { binder = new AnnotateDataBinder(w); binder.loadAll(); // ws = Workspace.getWorkspace(); } public void doOnCreateCommon(Window w, Event fe) throws Exception { doOnCreateCommon(w); CreateEvent ce = (CreateEvent) ((ForwardEvent) fe).getOrigin(); args = (Map<String, Object>) ce.getArg(); } public BaseCtrl() { super(); } @Override public void afterCompose() { processRecursive(this, this); Components.wireVariables(this, this); // auto wire variables Components.addForwards(this, this); // auto forward } /* if there are inner windows. than wire these too. * */ private void processRecursive(Window main, Window child) { Components.wireVariables(main, child); Components.addForwards(main, this); List<Component> winList = (List<Component>) child.getChildren(); for (Component window : winList) { if (window instanceof Window) { processRecursive(main, (Window) window); } } } }
branchDialog.zul
<?xml version="1.0" encoding="UTF-8"?> <?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?> <zk xmlns="http://www.zkoss.org/2005/zul" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd"> <window id="branchDialogWindow" title="Branches" border="normal" use="org.myfirm.module.branch.BranchDialogCtrl" closable="true" width="450px" height="250px"> <borderlayout id="borderlayoutBranchDialog"> <north border="none" margins="0,0,0,0" size="90%"> <div id="divNorthBranchDialog"> <toolbar> <toolbarbutton image="/images/icons/page_detail.gif" /> <toolbarbutton image="/images/icons/find.gif" /> </toolbar> <panel title="Branche" style="margin-bottom:10px" border="normal" collapsible="true"> <panelchildren> <grid fixedLayout="true" style="border:0px"> <columns> <column width="150px" /> <column width="100%" /> </columns> <rows> <row> Branch No.: <textbox id="braNr" width="100px" /> </row> <row> <separator bar="true"></separator> <separator bar="true"></separator> </row> <row> Branch Name: <textbox id="braBezeichnung" width="100%" /> </row> </rows> </grid> </panelchildren> </panel> </div> </north> <east border="none"></east> <center border="none"></center> <west border="none"></west> <south border="none" margins="1,0,0,0" size="26px" splittable="false"> <div id="divSouthCustomer" align="right"> <grid> <rows> <row valign="middle"> <hbox align="end"> <button id="btnNew" height="20" label="new"> </button> <button id="btnEdit" height="20" label="edit"> </button> <button id="btnDelete" height="20" label="delete"> </button> <button id="btnSave" height="20" label="save"> </button> <button id="btnClose" height="20" label="close"> </button> </hbox> </row> </rows> </grid> </div> </south> </borderlayout> </window> </zk>
The controller for the modal dialog
branchDialogCtrl.java
* This is the controller class for the branch dialog described * in the branchDialog.zul file. * * In this dialog we can do the mainly database oriented methods like * new, edit, save, delete a branch. * * * */ package org.myfirm.module.branch; import org.apache.log4j.Logger; import org.myfirm.util.BaseCtrl; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zkplus.spring.SpringUtil; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Listbox; import org.zkoss.zul.Messagebox; import org.zkoss.zul.Textbox; import org.zkoss.zul.Window; import de.daibutsu.backend.model.Branche; import de.daibutsu.backend.service.BrancheService; public class BranchDialogCtrl extends BaseCtrl { private static Logger logger = Logger.getLogger(BranchDialogCtrl.class); private static final long serialVersionUID = -546886879998950467L; /* * All the components that are defined here and have a corresponding * component with the same 'id' in the zul-file are getting autowired. * Remember our 'extends BaseCtrl' class do extends Window and implements * AfterCompose. * * @Override public void afterCompose() { * * Components.wireVariables(this, this); // auto wire variables * Components.addForwards(this, this); // auto forward } * * So, we need not such a cruel thing like * * Window w = branchDialogWindow; * braNr = (Textbox) w.getPage().getFellow("branchDialogWindow").getFellow("braNr"); */ // Components from the zul-file that are autowired private Window branchDialogWindow; // the window 'id' from the zul-file private Textbox braNr; // autowire private Textbox braBezeichnung; // autowire // not wired vars private Listbox lbBranch; // overhanded per param private Branche branche; // overhanded per param private BranchListCtrl branchCtrl; // overhanded per param private BrancheService brancheService; public BrancheService getBrancheService() { if (brancheService == null) { brancheService = (BrancheService) SpringUtil.getBean("brancheService"); setBrancheService(brancheService); } return brancheService; } public void setBrancheService(BrancheService brancheService) { this.brancheService = brancheService; } public Branche getBranche() { return branche; } public void setBranche(Branche branche) { this.branche = branche; } /** * constructor */ public BranchDialogCtrl() { super(); } /** * Before binding branches data and calling the dialog window we do check, * if the zul-file is called with a parameter for a selected branch object * in a Map. * * @param event * @throws Exception */ public void onCreate$branchDialogWindow(Event event) throws Exception { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doOnCreateCommon(branchDialogWindow, event); // autowire the vars if (args.containsKey("branche")) { branche = (Branche) args.get("branche"); setBranche(branche); } else { setBranche(null); } // we get the listBox Object for the branch list. So we have access // to it and can synchronize the shown data when we do insert, edit or // delete branches here. if (args.containsKey("lbBranch")) { lbBranch = (Listbox) args.get("lbBranch"); } else { lbBranch = null; } if (args.containsKey("branchCtrl")) { branchCtrl = (BranchListCtrl) args.get("branchCtrl"); } else { branchCtrl = null; } showBranchDialog(getBranche()); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++ Button events +++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * when the "save" button is clicked. * * @param event */ public void onClick$btnSave(Event event) { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doSave(); } /** * when the "edit" button is clicked. * * @param event */ public void onClick$btnEdit(Event event) { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doEdit(); } /** * when the "new" button is clicked. * * @param event */ public void onClick$btnNew(Event event) { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doNew(); } /** * when the "delete" button is clicked. * * @param event */ public void onClick$btnDelete(Event event) throws InterruptedException { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doDelete(); } /** * when the "close" button is clicked. * * @param event */ public void onClick$btnClose(Event event) throws InterruptedException { if (logger.isInfoEnabled()) { logger.info("--> " + event.toString()); } doClose(); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++ GUI operations +++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * closes the dialog window. */ private void doClose() { branchDialogWindow.onClose(); } /** * opens the dialog window in modal mode. */ public void showBranchDialog(Branche branche) throws InterruptedException { // if customer == null then we opened the customerDialog.zul without // args for a given customer, so we do a new Branche() if (branche == null) { branche = new Branche(); } // set Readonly mode accordingly if the object is new or not. if (branche.isNew()) { doEdit(); } else { doReadOnly(); } try { // fill the components with the data braNr.setValue(branche.getBraNr()); braBezeichnung.setValue(branche.getBraBezeichnung()); branchDialogWindow.doModal(); // open the dialog in modal mode } catch (Exception e) { Messagebox.show(e.toString()); } } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++ crud operations +++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ private void doDelete() throws InterruptedException { final Branche branche = getBranche(); // Show a confirm box String msg = "Are you sure to delete this branch ? /n/b /n/b" + branche.getBraBezeichnung() + " ,"; if (Messagebox.show(msg, "Deleting a branch", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION, new EventListener() { public void onEvent(Event evt) { switch (((Integer) evt.getData()).intValue()) { case Messagebox.YES: deleteBranch(); case Messagebox.NO: break; // } } private void deleteBranch() { // delete from database getBrancheService().delete(branche); // now synchronize the branches listBox ListModelList lml = (ListModelList) lbBranch.getListModel(); // Check if the branch object is new or updated // -1 means that the obj is not in the list, so it's new. if (lml.indexOf(branche) == -1) { } else { lml.remove(lml.indexOf(branche)); } branchDialogWindow.onClose(); // close the dialog } } ) == Messagebox.YES) { } } private void doNew() { Branche branche = new Branche(); setBranche(branche); doClear(); // clear all commponents doEdit(); // edit mode } private void doEdit() { braNr.setReadonly(false); braBezeichnung.setReadonly(false); } public void doReadOnly() { braNr.setReadonly(true); braBezeichnung.setReadonly(true); } public void doClear() { braNr.setValue(""); braBezeichnung.setValue(""); } public void doSave() { Branche branche = getBranche(); // fill the customer object with the components data branche.setBraNr(braNr.getValue()); branche.setBraBezeichnung(braBezeichnung.getValue()); // save to database getBrancheService().saveOrUpdate(branche); // now synchronize the branches listBox ListModelList lml = (ListModelList) lbBranch.getListModel(); // Check if the branch object is new or updated // -1 means that the obj is not in the list, so its new. if (lml.indexOf(branche) == -1) { lml.add(branche); } else { lml.set(lml.indexOf(branche), branche); } doReadOnly(); } }
Branch.java Domain/Model class
package de.daibutsu.backend.model; // Generated 18.10.2008 19:00:08 by Hibernate Tools 3.2.2.GA import java.util.HashSet; import java.util.Set; /** * Branche generated by hbm2java */ public class Branche implements java.io.Serializable { private static final long serialVersionUID = -8799762516266595746L; private long braId = Long.MIN_VALUE; private int version; private String braNr; private String braBezeichnung; private Set<Kunde> kundes = new HashSet<Kunde>(0); public boolean isNew() { return (getBraId() == Long.MIN_VALUE); } public Branche() { } public Branche(long braId, String braBezeichnung) { this.braId = braId; this.braBezeichnung = braBezeichnung; } public Branche(long braId, String braNr, String braBezeichnung, Set<Kunde> kundes) { this.braId = braId; this.braNr = braNr; this.braBezeichnung = braBezeichnung; this.kundes = kundes; } public long getBraId() { return this.braId; } public void setBraId(long braId) { this.braId = braId; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getBraNr() { return this.braNr; } public void setBraNr(String braNr) { this.braNr = braNr; } public String getBraBezeichnung() { return this.braBezeichnung; } public void setBraBezeichnung(String braBezeichnung) { this.braBezeichnung = braBezeichnung; } public Set<Kunde> getKundes() { return this.kundes; } public void setKundes(Set<Kunde> kundes) { this.kundes = kundes; } @Override public int hashCode() { return Long.valueOf(getBraId()).hashCode(); } public boolean equals(Branche branche) { return getBraId() == branche.getBraId(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Branche) { Branche branche = (Branche) obj; return equals(branche); } return false; } }
@terrytornado
I'm trying your concept but I have some rendering issue:
In java code I have:
....
List<Oseba> osebe = new ArrayList<Oseba>();
// get list from DB
osebe = oseba_db.findOsebe(oseba);
// populate Listbox
ListModelList list = new ListModelList(osebe);
search_result.setModel(list);
// add custom rendering
search_result.setItemRenderer(new OsebaListModelItemRenderer());
OsebaListModelItemRenderer.java
@Override
public void render(Listitem item, Object data) throws Exception {
new Listcell(((Oseba)data).getIme()).setParent(item);
new Listcell(((Oseba)data).getPriimek()).setParent(item);
}
In zul I have:
<listbox id="search_result">
<listhead sizable="false">
<listheader label="Ime"/>
<listheader label="Priimek"/>
</listhead>
</listbox>
Problem:
But when the listbox is populate I get only one column(first one) what I'm doing wrong
Hi,
first, check if the List have really more than one entry
// get list from DB osebe = oseba_db.findOsebe(oseba); ?????? System.out.println(oseba.size())
Stephan
PS: please use the CODE tag for better reading source code.
public class OsebaWire extends GenericAutowireComposer { .... // get list from DB osebe = oseba_db.findOsebe(oseba); // size is 10 }
Ok, this is no longer a problem it display.
But next problem is when I implement double click:
public class OsebaListModelItemRenderer implements ListitemRenderer { @Override public void render(Listitem item, Object data) throws Exception { new Listcell(((Oseba)data).getIme()).setParent(item); new Listcell(((Oseba)data).getPriimek()).setParent(item); ComponentsCtrl.applyForward(item, "onDoubleClick=onDoubleClicked"); } } ... @SuppressWarnings("unchecked") public void onDoubleClicked(Event event) throws Exception { System.out.print("\n klik"); // get the selected object Listitem item = search_result.getSelectedItem(); if (item != null) { // store the selected customer object Oseba izbrana_oseba = (Oseba) item.getAttribute("data"); select_ime.setValue(izbrana_oseba.getIme()); select_pri.setValue(izbrana_oseba.getPriimek()); } }
So, the problem of onDoubleClicked method is that item.getAttribute("data") is null.
Any suggestion ?
Best regards, Toamz
Asked: 2009-01-22 16:21:47 +0800
Seen: 7,679 times
Last updated: May 19 '09