All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ioc.commons.ui.impl.HasVisibilityAdapter Maven / Gradle / Ivy

package org.ioc.commons.ui.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.ioc.commons.ui.HasVisibility;
import org.ioc.commons.ui.IsWidget;

public class HasVisibilityAdapter implements HasVisibility {

	protected boolean visible = true;
	private OnChangeCommand onChangeCommand;

	public HasVisibilityAdapter() {
		// Nothing
	}

	public HasVisibilityAdapter(boolean initialVisibleValue) {
		this.visible = initialVisibleValue;
	}

	@Override
	public void setVisible(boolean visible) {
		// Override me
		boolean changed = (visible != this.visible);
		this.visible = visible;
		if (this.onChangeCommand != null && changed) {
			this.onChangeCommand.execute(visible);
		}

	}

	@Override
	public boolean isVisible() {
		return visible;
	}

	private static final Map globalFields = new HashMap();

	/**
	 * It creates a new adapter instance for a field owned by a widget and keep
	 * it in memory for reusing in the next calls. The widget will be
	 * responsible for cleaning them from memory when it is not going to use
	 * them anymore by calling cleaningAdapter() method.
	 * 
	 * @param fieldName
	 *            Unique name of the field on the owner
	 * @param fieldOwner
	 *            The owner of the field
	 * @return An unique instance for this field in this field owner.
	 */
	public static  HasVisibilityAdapter forField(String fieldName, IsWidget fieldOwner) {
		HasVisibilityAdapter adapter = forField(fieldName, fieldOwner, true);
		return adapter;
	}

	public static HasVisibilityAdapter forField(String fieldName, IsWidget fieldOwner, boolean initialValue) {
		Field field = new Field(fieldName, fieldOwner);
		HasVisibilityAdapter adapter = globalFields.get(field);
		if (adapter == null) {
			adapter = new HasVisibilityAdapter(initialValue);
			globalFields.put(field, adapter);
		}
		return (HasVisibilityAdapter) adapter;
	}

	/**
	 * Clean all the instantiated adapters for this owner using
	 * {@link HasVisibilityAdapter#forField(String, IsWidget)} method.
	 * 
	 * @param fromOwner
	 *            Owner of the fields
	 */
	public static void cleanAdapters(IsWidget fromOwner) {
		cleanAdapters((Object) fromOwner);
	}

	public static void cleanAdapters(Object fromField) {
		for (Iterator it = globalFields.keySet().iterator(); it.hasNext();) {
			Field field = it.next();
			if (fromField.equals(field.getFieldOwner())) {
				it.remove();
			}
		}
	}

	/**
	 * Set a command to be executed when a change is produced.
	 * 
	 * @param onChangeCommand
	 *            Command to be executed.
	 * @return This adapter
	 */
	final public HasVisibilityAdapter onChange(OnChangeCommand onChangeCommand) {
		this.onChangeCommand = onChangeCommand;
		return this;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy