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

net.sf.mgp.javafx.property.NestedReadOnlyJavaBeanObjectProperty Maven / Gradle / Ivy

package net.sf.mgp.javafx.property;

import javafx.beans.property.ReadOnlyObjectPropertyBase;
import javafx.beans.property.adapter.ReadOnlyJavaBeanObjectPropertyBuilder;
import javafx.beans.property.adapter.ReadOnlyJavaBeanProperty;

class NestedReadOnlyJavaBeanObjectProperty extends ReadOnlyObjectPropertyBase implements ReadOnlyJavaBeanProperty {

	private final String property;
	private final ReadOnlyJavaBeanProperty parent;
	private final ParentListener listener;
	private Object bean;
	private Object value;

	public NestedReadOnlyJavaBeanObjectProperty(ReadOnlyJavaBeanProperty parent, String property) {
		this.parent = parent;
		this.property = property;
		listener = new ParentListener();
		parent.addListener(listener);
		bean = parent.getValue();
		if (parent.getValue() != null) {
			listener.bindTo(parent.getValue());
		}
	}

	@Override
	public void fireValueChangedEvent() {
		parent.fireValueChangedEvent();
		super.fireValueChangedEvent();
		listener.fireValueChangedEvent();
	}

	@Override
	public void dispose() {
		listener.dispose();
		parent.removeListener(listener);
		bean = null;
		value = null;
		parent.dispose();
	}

	@Override
	public Object getBean() {
		return bean;
	}

	private void setBean(Object bean) {
		this.bean = bean;
	}

	@Override
	public String getName() {
		return property;
	}

	@Override
	public Object get() {
		return value;
	}

	private void internalSet(Object newValue) {
		value = newValue;
		super.fireValueChangedEvent();
	}

	private class ParentListener extends AbstractParentListener> {
		public ParentListener() {
			super(NestedReadOnlyJavaBeanObjectProperty.this::setBean, NestedReadOnlyJavaBeanObjectProperty.this::internalSet);
		}

		@Override
		protected ReadOnlyJavaBeanProperty createProperty(Object bean) {
			try {
				return ReadOnlyJavaBeanObjectPropertyBuilder.create().bean(bean).name(property).build();
			} catch (NoSuchMethodException e) {
				throw new IllegalArgumentException("Illegal property " + property, e);
			}
		}
	}
}