Java Code Examples for javafx.beans.value.ObservableValue#addListener()

The following examples show how to use javafx.beans.value.ObservableValue#addListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConditionalBinding.java    From EasyBind with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ConditionalBinding(
        Property<T> target,
        ObservableValue<? extends T> source,
        ObservableValue<Boolean> condition) {
    this.target = new WeakReference<>(target);
    this.source = source;
    this.condition = condition;

    // add an empty listener to target just to maintain a strong reference
    // to this object for the lifetime of target
    target.addListener(this);

    condition.addListener((ChangeListener<Boolean>) this);

    if(condition.getValue()) {
        target.bind(source);
    }
}
 
Example 2
Source File: MultisetPropertyBase.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void bind(
		final ObservableValue<? extends ObservableMultiset<E>> observedValue) {
	if (observedValue == null) {
		// While according to GEF conventions we would rather throw an
		// IllegalArgumentException here, JavaFX seems to request an NPE.
		throw new NullPointerException("Cannot bind to null.");
	}
	if (!observedValue.equals(this.observedValue)) {
		unbind();
		this.observedValue = observedValue;
		if (invalidatingObservedValueObserver == null) {
			invalidatingObservedValueObserver = new InvalidatingObserver<>(
					this);
		}
		observedValue.addListener(invalidatingObservedValueObserver);
		markInvalid(value);
	}
}
 
Example 3
Source File: SetMultimapPropertyBase.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void bind(
		final ObservableValue<? extends ObservableSetMultimap<K, V>> observedValue) {
	if (observedValue == null) {
		// While according to GEF conventions we would rather throw an
		// IllegalArgumentException here, JavaFX seems to request an NPE.
		throw new NullPointerException("Cannot bind to null.");
	}
	if (!observedValue.equals(this.observedValue)) {
		unbind();
		this.observedValue = observedValue;
		if (invalidatingObservedValueObserver == null) {
			invalidatingObservedValueObserver = new InvalidatingObserver<>(
					this);
		}
		observedValue.addListener(invalidatingObservedValueObserver);
		markInvalid(value);
	}
}
 
Example 4
Source File: AbstractNumericDolphinBinder.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Binding toNumeric(final ObservableValue<Number> observableValue) {
    if (observableValue == null) {
        throw new IllegalArgumentException("observableValue must not be null");
    }
    final ChangeListener<Number> listener = (obs, oldVal, newVal) -> {
        if (!equals(newVal, property.get())) {
            property.set(getConverter().convert(newVal));
        }
    };
    observableValue.addListener(listener);
    if (!equals(observableValue.getValue(), property.get())) {
        property.set(getConverter().convert(observableValue.getValue()));
    }
    return () -> observableValue.removeListener(listener);
}
 
Example 5
Source File: CollectionBindings.java    From phoenicis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Maps an {@link ObservableValue<I>} object to an {@link ObservableMap} by applying the given converter function
 * and adding the result to the {@link ObservableMap}.
 * In case the input value is empty, i.e. contains <code>null</code>, the returned {@link ObservableMap} is also
 * empty
 *
 * @param property The input value
 * @param converter The converter function
 * @param <I> The type of the input value
 * @param <O1> The input type of the result map
 * @param <O2> The output type of the result map
 * @return A {@link ObservableMap} containing the converted map
 */
public static <I, O1, O2> ObservableMap<O1, O2> mapToMap(ObservableValue<I> property,
        Function<I, Map<O1, O2>> converter) {
    final ObservableMap<O1, O2> result = FXCollections.observableHashMap();

    final InvalidationListener listener = (Observable invalidation) -> {
        final I input = property.getValue();

        result.clear();

        if (input != null) {
            result.putAll(converter.apply(input));
        }
    };

    // add the listener to the property
    property.addListener(listener);

    // ensure that the result map is initialised correctly
    listener.invalidated(property);

    return result;
}
 
Example 6
Source File: PropertyTracker.java    From scenic-view with GNU General Public License v3.0 5 votes vote down vote up
public void setTarget(final Object target) {
    properties.clear();
    // Using reflection, locate all properties and their corresponding
    // property references
    for (final Method method : target.getClass().getMethods()) {
        if (method.getName().endsWith("Property")) {
            try {
                final Class returnType = method.getReturnType();
                if (ObservableValue.class.isAssignableFrom(returnType)) {
                    // we've got a winner
                    final String propertyName = method.getName().substring(0, method.getName().lastIndexOf("Property"));
                    // Request access
                    method.setAccessible(true);
                    final ObservableValue property = (ObservableValue) method.invoke(target);
                    properties.put(property, propertyName);
                }
            } catch (final Exception e) {
                ExceptionLogger.submitException(e, "Failed to get property " + method.getName());
            }
        }
    }

    for (final ObservableValue ov : properties.keySet()) {
        if (ov != null && propListener != null) {
            ov.addListener(propListener);
        }
    }
}
 
Example 7
Source File: Val.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static <T> Subscription observeChanges(
        ObservableValue<? extends T> obs,
        ChangeListener<? super T> listener) {
    if(obs instanceof Val) {
        return ((Val<? extends T>) obs).observeChanges(listener);
    } else {
        obs.addListener(listener);
        return () -> obs.removeListener(listener);
    }
}
 
Example 8
Source File: When.java    From EasyBind with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ConditionalSubscription(
        ObservableValue<Boolean> condition,
        Supplier<? extends Subscription> bindFn) {
    this.condition = condition;
    this.bindFn = bindFn;

    condition.addListener(conditionListener);
    if(condition.getValue()) {
        subscription = bindFn.get();
    }
}
 
Example 9
Source File: DefaultDolphinBinder.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Binding to(final ObservableValue<T> observableValue, final Converter<? super T, ? extends S> converter) {
    if (observableValue == null) {
        throw new IllegalArgumentException("observableValue must not be null");
    }
    if (converter == null) {
        throw new IllegalArgumentException("converter must not be null");
    }
    final ChangeListener<T> listener = (obs, oldVal, newVal) -> property.set(converter.convert(newVal));
    observableValue.addListener(listener);
    property.set(converter.convert(observableValue.getValue()));
    return () -> observableValue.removeListener(listener);
}
 
Example 10
Source File: JFXNodeUtils.java    From JFoenix with Apache License 2.0 5 votes vote down vote up
public static <T> InvalidationListener addDelayedPropertyInvalidationListener(ObservableValue<T> property,
                                                                              Duration delayTime,
                                                                              Consumer<T> justInTimeConsumer,
                                                                              Consumer<T> delayedConsumer) {
    Wrapper<T> eventWrapper = new Wrapper<>();
    PauseTransition holdTimer = new PauseTransition(delayTime);
    holdTimer.setOnFinished(event -> delayedConsumer.accept(eventWrapper.content));
    final InvalidationListener invalidationListener = observable -> {
        eventWrapper.content = property.getValue();
        justInTimeConsumer.accept(eventWrapper.content);
        holdTimer.playFromStart();
    };
    property.addListener(invalidationListener);
    return invalidationListener;
}
 
Example 11
Source File: JFXNodeUtils.java    From JFoenix with Apache License 2.0 5 votes vote down vote up
public static <T> InvalidationListener addDelayedPropertyInvalidationListener(ObservableValue<T> property,
                                                                              Duration delayTime,
                                                                              BiConsumer<T, InvalidationListener> consumer) {
    Wrapper<T> eventWrapper = new Wrapper<>();
    PauseTransition holdTimer = new PauseTransition(delayTime);
    final InvalidationListener invalidationListener = observable -> {
        eventWrapper.content = property.getValue();
        holdTimer.playFromStart();
    };
    holdTimer.setOnFinished(event -> consumer.accept(eventWrapper.content, invalidationListener));
    property.addListener(invalidationListener);
    return invalidationListener;
}
 
Example 12
Source File: JFXNodeUtils.java    From JFoenix with Apache License 2.0 5 votes vote down vote up
public static <T> InvalidationListener addDelayedPropertyInvalidationListener(ObservableValue<T> property,
                                                                              Duration delayTime,
                                                                              Consumer<T> consumer) {
    Wrapper<T> eventWrapper = new Wrapper<>();
    PauseTransition holdTimer = new PauseTransition(delayTime);
    holdTimer.setOnFinished(event -> consumer.accept(eventWrapper.content));
    final InvalidationListener invalidationListener = observable -> {
        eventWrapper.content = property.getValue();
        holdTimer.playFromStart();
    };
    property.addListener(invalidationListener);
    return invalidationListener;
}
 
Example 13
Source File: FX.java    From FxDock with Apache License 2.0 5 votes vote down vote up
/** adds a ChangeListener to the specified ObservableValue(s) */
public static void onChange(Runnable handler, boolean fireImmediately, ObservableValue<?> ... props)
{
	for(ObservableValue<?> p: props)
	{
		// weak listener gets collected... but why??
		p.addListener((src,prev,cur) -> handler.run());
	}
	
	if(fireImmediately)
	{
		handler.run();
	}
}
 
Example 14
Source File: FontIconTableCell.java    From ikonli with Apache License 2.0 5 votes vote down vote up
@Override
public void updateItem(T item, boolean empty) {
    super.updateItem(item, empty);

    if (empty) {
        setGraphic(null);
    } else {
        if (subscription != null) {
            subscription.unsubscribe();
            subscription = null;
        }

        final TableColumn<S, T> column = getTableColumn();
        ObservableValue<T> observable = column == null ? null : column.getCellObservableValue(getIndex());

        if (observable != null) {
            ChangeListener<T> listener = (v, o, n) -> setIconCode(n);
            observable.addListener(listener);
            subscription = () -> observable.removeListener(listener);
            setIconCode(observable.getValue());
        } else if (item != null) {
            setIconCode(item);
        }

        setGraphic(icon);
        setAlignment(Pos.CENTER);
    }
}
 
Example 15
Source File: Controller.java    From xdat_editor with MIT License 5 votes vote down vote up
private TreeView<Object> createTreeView(Field listField, ObservableValue<String> filter) {
    TreeView<Object> elements = new TreeView<>();
    elements.setCellFactory(param -> new TreeCell<Object>() {
        @Override
        protected void updateItem(Object item, boolean empty) {
            super.updateItem(item, empty);

            if (item == null || empty) {
                setText(null);
                setGraphic(null);
            } else {
                setText(item.toString());
                if (UIEntity.class.isAssignableFrom(item.getClass())) {
                    try (InputStream is = getClass().getResourceAsStream("/acmi/l2/clientmod/xdat/nodeicons/" + UI_NODE_ICONS.getOrDefault(item.getClass().getSimpleName(), UI_NODE_ICON_DEFAULT))) {
                        setGraphic(new ImageView(new Image(is)));
                    } catch (IOException ignore) {}
                }
            }
        }
    });
    elements.setShowRoot(false);
    elements.setContextMenu(createContextMenu(elements));

    InvalidationListener treeInvalidation = (observable) -> buildTree(editor.xdatObjectProperty().get(), listField, elements, filter.getValue());
    editor.xdatObjectProperty().addListener(treeInvalidation);
    xdatListeners.add(treeInvalidation);

    filter.addListener(treeInvalidation);

    return elements;
}
 
Example 16
Source File: CountingListener.java    From ReactFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public CountingListener(ObservableValue<?> observable) {
    this.observable = observable;
    observable.addListener(this);
}
 
Example 17
Source File: Val.java    From ReactFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
static Subscription observeInvalidations(
        ObservableValue<?> obs,
        InvalidationListener listener) {
    obs.addListener(listener);
    return () -> obs.removeListener(listener);
}
 
Example 18
Source File: FlatMap.java    From EasyBind with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public FlatMapBindingBase(ObservableValue<T> src, Function<? super T, O> f) {
    this.src = src;
    this.mapper = f;
    src.addListener(weakSrcListener);
}
 
Example 19
Source File: ShortTimeFourierTransformSample.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function to add an event handler to many properties
 */
private static void installEventHandlers(final InvalidationListener listener, final ObservableValue<?>... props) {
    for (final ObservableValue<?> prop : props) {
        prop.addListener(listener);
    }
}
 
Example 20
Source File: EasyBind.java    From EasyBind with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * Invokes {@code subscriber} for the current and every new value of
 * {@code observable}.
 * @param observable observable value to subscribe to
 * @param subscriber action to invoke for values of {@code observable}.
 * @return a subscription that can be used to stop invoking subscriber
 * for any further {@code observable} changes.
 */
public static <T> Subscription subscribe(ObservableValue<T> observable, Consumer<? super T> subscriber) {
    subscriber.accept(observable.getValue());
    ChangeListener<? super T> listener = (obs, oldValue, newValue) -> subscriber.accept(newValue);
    observable.addListener(listener);
    return () -> observable.removeListener(listener);
}