Starting from ZK 6, all information, including selection, opened objects, sorting and multiple selection, are now maintained in the model rather than within the components (listbox, combobox, etc.) for providing better flexibility Which means that two components are now able to share a common model.

However, in some use cases we may want two components to use the same data set but we also want them to have two independent selection states at the same time. For example we may have two comboboxes with a list of countries while one represents “departing country” and the other represents “destination country”.

This article will demonstrate how you can achieve this in ZK 6 in 2 ways.

1. Use a same data set with different data models:
In view model class, simply return different ListModelList instances for each components as illustrated below:

public class ComboboxVM {
    private List<String> list = new ArrayList<String>();
    public ComboboxVM() {
        for (int i = 1; i < 11; i++)
        list.add("option " + i);
    }
    public ListModel<String> getModel() {
        return new ListModelList<String>(list);
    }
}

2. Create a custom data model class:

If your application allows only one data model, then we can create another custom model class that wraps the origin data model:

First, create a CustomListModel class that extends AbstractListModel, and override newEmptySelection method to separate the selection states.

public class CustomListModel<E> extends AbstractListModel<E> {
	private ListModel<E> _model;
	public CustomListModel(ListModel<E> model) {
		_model = model;
	}
	protected Set<E> newEmptySelection() {
		return new LinkedHashSet<E>();
	}
	public E getElementAt(int index) {
		return _model.getElementAt(index);
	}
	public int getSize() {
		return _model.getSize();
	}
}

Then, use CustomListModel in your view model

public class ComboboxVM {
    private List<String> list = new ArrayList<String>();
    private ListModel<String> listModel;
    public ComboboxVM() {
        for (int i = 1; i < 11; i++)
            list.add("option " + i);
        listModel = new ListModelList<String>(list);
    }
    public ListModel<String> getModel() {
        return new CustomListModel<String>(listModel);
    }
}

In this article I have shown you two ways of how you can share a common data set in ZK 6. If there are any feedback, please feel free to express yourself.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

2 Responses to “Sharing a common data model for multiple components in ZK 6”

  1. Ron Grimes says:

    At the end, you say, “Then, use CustomListModel in your view model”, but then never actually use CustomListModel in your view.

  2. vincentjian says:

    Hi Ron,
    Thanks for point out the typo. Already updated.

Leave a Reply