Java Code Examples for javafx.beans.binding.Bindings#createObjectBinding()

The following examples show how to use javafx.beans.binding.Bindings#createObjectBinding() . 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: TestDatatypes.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void simpleAvgBinding() {
  Property<Double> a = new SimpleObjectProperty<>();
  Property<Double> b = new SimpleObjectProperty<>();
  Property<Double>[] properties = new Property[] {a, b};
  Property<Double> avg = new SimpleObjectProperty<>();

  ObjectBinding<Double> avgBinding = Bindings.createObjectBinding(() -> {
    double sum = 0;
    int n = 0;
    for (Property<Double> p : properties) {
      if (p.getValue() != null) {
        sum += p.getValue().doubleValue();
        n++;
      }
    }
    return n == 0 ? 0 : sum / n;
  }, properties);
  avg.bind(avgBinding);
  logger.info("avg=" + avg.getValue().doubleValue() + "   " + avg.getValue());
  a.setValue(10d);
  logger.info("avg=" + avg.getValue().doubleValue() + "   " + avg.getValue());
  b.setValue(5d);
  logger.info("avg=" + avg.getValue().doubleValue() + "   " + avg.getValue());
}
 
Example 2
Source File: DoubleRangeType.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ObjectBinding<?> createBinding(BindingsType bind, ModularFeatureListRow row) {
  // get all properties of all features
  @SuppressWarnings("unchecked")
  Property<Range<Double>>[] prop =
      row.streamFeatures().map(f -> f.get(this)).toArray(Property[]::new);
  switch (bind) {
    case RANGE:
      return Bindings.createObjectBinding(() -> {
        Range<Double> result = null;
        for (Property<Range<Double>> p : prop) {
          if (p.getValue() != null) {
            if (result == null)
              result = p.getValue();
            else
              result = result.span(p.getValue());
          }
        }
        return result;
      }, prop);
    case AVERAGE:
    case MIN:
    case MAX:
    case SUM:
    case COUNT:
    default:
      throw new UndefinedRowBindingException(this, bind);
  }
}
 
Example 3
Source File: IntegerRangeType.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ObjectBinding<?> createBinding(BindingsType bind, ModularFeatureListRow row) {
  // get all properties of all features
  @SuppressWarnings("unchecked")
  Property<Range<Integer>>[] prop =
      row.streamFeatures().map(f -> f.get(this)).toArray(Property[]::new);
  switch (bind) {
    case RANGE:
      return Bindings.createObjectBinding(() -> {
        Range<Integer> result = null;
        for (Property<Range<Integer>> p : prop) {
          if (p.getValue() != null) {
            if (result == null)
              result = p.getValue();
            else
              result = result.span(p.getValue());
          }
        }
        return result;
      }, prop);
    case AVERAGE:
    case MIN:
    case MAX:
    case SUM:
    case COUNT:
    default:
      throw new UndefinedRowBindingException(this, bind);
  }
}
 
Example 4
Source File: FloatRangeType.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ObjectBinding<?> createBinding(BindingsType bind, ModularFeatureListRow row) {
  // get all properties of all features
  @SuppressWarnings("unchecked")
  Property<Range<Float>>[] prop =
      row.streamFeatures().map(f -> f.get(this)).toArray(Property[]::new);
  switch (bind) {
    case RANGE:
      return Bindings.createObjectBinding(() -> {
        Range<Float> result = null;
        for (Property<Range<Float>> p : prop) {
          if (p.getValue() != null) {
            if (result == null)
              result = p.getValue();
            else
              result = result.span(p.getValue());
          }
        }
        return result;
      }, prop);
    case AVERAGE:
    case MIN:
    case MAX:
    case SUM:
    case COUNT:
    default:
      throw new UndefinedRowBindingException(this, bind);
  }
}
 
Example 5
Source File: GenericBackendDialogN5.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private Node initializeNode(
		final Node rootNode,
		final String datasetPromptText,
		final Node browseNode)
{
	final MenuButton datasetDropDown = new MenuButton();
	final StringBinding datasetDropDownText = Bindings.createStringBinding(() -> dataset.get() == null || dataset.get().length() == 0 ? datasetPromptText : datasetPromptText + ": " + dataset.get(), dataset);
	final ObjectBinding<Tooltip> datasetDropDownTooltip = Bindings.createObjectBinding(() -> Optional.ofNullable(dataset.get()).map(Tooltip::new).orElse(null), dataset);
	datasetDropDown.tooltipProperty().bind(datasetDropDownTooltip);
	datasetDropDown.disableProperty().bind(this.isN5Valid.not());
	datasetDropDown.textProperty().bind(datasetDropDownText);
	datasetChoices.addListener((ListChangeListener<String>) change -> {
		final MatchSelection matcher = MatchSelection.fuzzySorted(datasetChoices, s -> {
			dataset.set(s);
			datasetDropDown.hide();
		});
		LOG.debug("Updating dataset dropdown to fuzzy matcher with choices: {}", datasetChoices);
		final CustomMenuItem menuItem = new CustomMenuItem(matcher, false);
		// clear style to avoid weird blue highlight
		menuItem.getStyleClass().clear();
		datasetDropDown.getItems().setAll(menuItem);
		datasetDropDown.setOnAction(e -> {datasetDropDown.show(); matcher.requestFocus();});
	});
	final GridPane grid = new GridPane();
	grid.add(rootNode, 0, 0);
	grid.add(datasetDropDown, 0, 1);
	GridPane.setHgrow(rootNode, Priority.ALWAYS);
	GridPane.setHgrow(datasetDropDown, Priority.ALWAYS);
	grid.add(browseNode, 1, 0);

	return grid;
}
 
Example 6
Source File: SysstringPropertyEditor.java    From xdat_editor with MIT License 5 votes vote down vote up
@Override
protected ObservableValue<Integer> getObservableValue() {
    if (value == null) {
        value = Bindings.createObjectBinding(() -> getEditor().getText().isEmpty() ? 0 : Integer.parseInt(getEditor().getText()), getEditor().textProperty());
    }
    return value;
}
 
Example 7
Source File: EntityIcon.java    From clarity-analyzer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected ObjectBinding<Paint> getTeamColor() {
    IntegerBinding teamNum = getTeamNum();
    return Bindings.createObjectBinding(() -> {
        int n = teamNum.get();
        switch (n) {
            case 2:
                return Color.GREEN;
            case 3:
                return Color.RED;
            default:
                return Color.GRAY;
        }
    }, teamNum);
}
 
Example 8
Source File: EntityIcon.java    From clarity-analyzer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected ObjectBinding<Paint> getPlayerColor() {
    IntegerBinding playerId = getPlayerId();
    return Bindings.createObjectBinding(() -> {
        int n = playerId.get();
        if (n < 0 || n > 9) {
            return Color.WHITE;
        } else {
            return PLAYER_COLORS[n];
        }
    }, playerId);
}
 
Example 9
Source File: ObservableEntity.java    From clarity-analyzer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public <T> ObjectBinding<T> getPropertyBinding(Class<T> propertyClass, String property, T defaultValue) {
    FieldPath fp = entity.getDtClass().getFieldPathForName(property);
    if (fp == null) {
        return Bindings.createObjectBinding(() -> defaultValue);
    } else {
        ObjectBinding<T> ob = getPropertyForFieldPath(fp).rawProperty();
        return Bindings.createObjectBinding(() -> ob.get(), ob);
    }
}
 
Example 10
Source File: VisualizerPresenter.java    From HdrHistogramVisualizer with Apache License 2.0 5 votes vote down vote up
void initializeIntervalChartAxes() {
    final NumberAxis xAxis = (NumberAxis) intervalChart.getXAxis();
    xAxis.setForceZeroInRange(false);

    // Bind X Tick label formatter to choice-box
    intervalXTickLabel.getItems().addAll(IntervalTickFormatter.values());
    intervalXTickLabel.getSelectionModel().select(0);
    ObjectBinding<StringConverter<Number>> intervalXLabelConverter = Bindings.createObjectBinding(
            () -> intervalXTickLabel.getSelectionModel().getSelectedItem().getConverter(),
            intervalXTickLabel.getSelectionModel().selectedItemProperty()
    );
    xAxis.tickLabelFormatterProperty().bind(intervalXLabelConverter);

}
 
Example 11
Source File: IntersectingSourceState.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
public <D extends IntegerType<D>, T extends Type<T>, B extends BooleanType<B>> IntersectingSourceState(
		final ThresholdingSourceState<?, ?> thresholded,
		final ConnectomicsLabelState<D, T> labels,
		final Composite<ARGBType, ARGBType> composite,
		final String name,
		final SharedQueue queue,
		final int priority,
		final Group meshesGroup,
		final ObjectProperty<ViewFrustum> viewFrustumProperty,
		final ObjectProperty<AffineTransform3D> eyeToWorldTransformProperty,
		final ObservableBooleanValue viewerEnabled,
		final ExecutorService manager,
		final HashPriorityQueueBasedTaskExecutor<MeshWorkerPriority> workers) {
	// TODO use better converter
	super(
			makeIntersect(thresholded, labels, queue, priority, name),
			new ARGBColorConverter.Imp0<>(0, 1),
			composite,
			name,
			// dependsOn:
			thresholded,
			labels);
	final DataSource<UnsignedByteType, VolatileUnsignedByteType> source = getDataSource();

	final MeshManagerWithAssignmentForSegments segmentMeshManager = labels.getMeshManager();

	this.labelsMeshesEnabledAndMeshesEnabled = Bindings.createBooleanBinding(
			() -> meshesEnabled.get() && segmentMeshManager.getManagedSettings().meshesEnabledProperty().get(),
			meshesEnabled,
			segmentMeshManager.getManagedSettings().meshesEnabledProperty());

	final BiFunction<TLongHashSet, Double, Converter<UnsignedByteType, BoolType>> getMaskGenerator = (l, minLabelRatio) -> (s, t) -> t.set(s.get() > 0);
	final SegmentMeshCacheLoader<UnsignedByteType>[] loaders = new SegmentMeshCacheLoader[getDataSource().getNumMipmapLevels()];
	Arrays.setAll(loaders, d -> new SegmentMeshCacheLoader<>(
			() -> getDataSource().getDataSource(0, d),
			getMaskGenerator,
			getDataSource().getSourceTransformCopy(0, d)));
	final GetMeshFor.FromCache<TLongHashSet> getMeshFor = GetMeshFor.FromCache.fromPairLoaders(loaders);

	this.fragmentsInSelectedSegments = new FragmentsInSelectedSegments(labels.getSelectedSegments());

	this.meshManager = new MeshManagerWithSingleMesh<>(
			source,
			getGetBlockListFor(segmentMeshManager.getLabelBlockLookup()),
			new WrappedGetMeshFromCache(getMeshFor),
			viewFrustumProperty,
			eyeToWorldTransformProperty,
			manager,
			workers,
			new MeshViewUpdateQueue<>());
	this.meshManager.viewerEnabledProperty().bind(viewerEnabled);
	final ObjectBinding<Color> colorProperty = Bindings.createObjectBinding(
			() -> Colors.toColor(this.converter().getColor()),
			this.converter().colorProperty());
	this.meshManager.colorProperty().bind(colorProperty);
	meshesGroup.getChildren().add(this.meshManager.getMeshesGroup());
	this.meshManager.getSettings().bindBidirectionalTo(segmentMeshManager.getSettings());
	this.meshManager.getRendererSettings().meshesEnabledProperty().bind(labelsMeshesEnabledAndMeshesEnabled);
	this.meshManager.getRendererSettings().blockSizeProperty().bind(segmentMeshManager.getRendererSettings().blockSizeProperty());
	this.meshManager.getRendererSettings().setShowBlockBounadries(false);
	this.meshManager.getRendererSettings().frameDelayMsecProperty().bind(segmentMeshManager.getRendererSettings().frameDelayMsecProperty());
	this.meshManager.getRendererSettings().numElementsPerFrameProperty().bind(segmentMeshManager.getRendererSettings().numElementsPerFrameProperty());
	this.meshManager.getRendererSettings().sceneUpdateDelayMsecProperty().bind(segmentMeshManager.getRendererSettings().sceneUpdateDelayMsecProperty());

	thresholded.getThreshold().minValue().addListener((obs, oldv, newv) -> {
		getMeshFor.invalidateAll();
		refreshMeshes(); });
	thresholded.getThreshold().maxValue().addListener((obs, oldv, newv) -> {
		getMeshFor.invalidateAll();
		refreshMeshes(); });

	fragmentsInSelectedSegments.addListener(obs -> refreshMeshes());
}
 
Example 12
Source File: IntersectingSourceState.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
@Deprecated
public <D extends IntegerType<D>, T extends Type<T>, B extends BooleanType<B>> IntersectingSourceState(
		final ThresholdingSourceState<?, ?> thresholded,
		final LabelSourceState<D, T> labels,
		final Composite<ARGBType, ARGBType> composite,
		final String name,
		final SharedQueue queue,
		final int priority,
		final Group meshesGroup,
		final ObjectProperty<ViewFrustum> viewFrustumProperty,
		final ObjectProperty<AffineTransform3D> eyeToWorldTransformProperty,
		final ObservableBooleanValue viewerEnabled,
		final ExecutorService manager,
		final HashPriorityQueueBasedTaskExecutor<MeshWorkerPriority> workers) {
	// TODO use better converter
	super(
			makeIntersect(thresholded, labels, queue, priority, name),
			new ARGBColorConverter.Imp0<>(0, 1),
			composite,
			name,
			// dependsOn:
			thresholded,
			labels);
	final DataSource<UnsignedByteType, VolatileUnsignedByteType> source = getDataSource();

	final MeshManagerWithAssignmentForSegments segmentMeshManager = labels.meshManager();
	final SelectedIds selectedIds = labels.selectedIds();

	this.labelsMeshesEnabledAndMeshesEnabled = Bindings.createBooleanBinding(
			() -> meshesEnabled.get() && segmentMeshManager.getManagedSettings().meshesEnabledProperty().get(),
			meshesEnabled,
			segmentMeshManager.getManagedSettings().meshesEnabledProperty());


	final BiFunction<TLongHashSet, Double, Converter<UnsignedByteType, BoolType>> getMaskGenerator = (l, minLabelRatio) -> (s, t) -> t.set(s.get() > 0);
	final SegmentMeshCacheLoader<UnsignedByteType>[] loaders = new SegmentMeshCacheLoader[getDataSource().getNumMipmapLevels()];
	Arrays.setAll(loaders, d -> new SegmentMeshCacheLoader<>(
			() -> getDataSource().getDataSource(0, d),
			getMaskGenerator,
			getDataSource().getSourceTransformCopy(0, d)));
	final GetMeshFor.FromCache<TLongHashSet> getMeshFor = GetMeshFor.FromCache.fromPairLoaders(loaders);

	final FragmentSegmentAssignmentState assignment                  = labels.assignment();
	final SelectedSegments               selectedSegments            = new SelectedSegments(selectedIds, assignment);
	this.fragmentsInSelectedSegments = new FragmentsInSelectedSegments(selectedSegments);

	this.meshManager = new MeshManagerWithSingleMesh<>(
			source,
			getGetBlockListFor(segmentMeshManager.getLabelBlockLookup()),
			new WrappedGetMeshFromCache(getMeshFor),
			viewFrustumProperty,
			eyeToWorldTransformProperty,
			manager,
			workers,
			new MeshViewUpdateQueue<>());
	this.meshManager.viewerEnabledProperty().bind(viewerEnabled);
	meshesGroup.getChildren().add(this.meshManager.getMeshesGroup());
	final ObjectBinding<Color> colorProperty = Bindings.createObjectBinding(
			() -> Colors.toColor(this.converter().getColor()),
			this.converter().colorProperty());
	this.meshManager.colorProperty().bind(colorProperty);
	this.meshManager.getSettings().bindBidirectionalTo(segmentMeshManager.getSettings());
	this.meshManager.getRendererSettings().meshesEnabledProperty().bind(labelsMeshesEnabledAndMeshesEnabled);
	this.meshManager.getRendererSettings().blockSizeProperty().bind(segmentMeshManager.getRendererSettings().blockSizeProperty());
	this.meshManager.getRendererSettings().setShowBlockBounadries(false);
	this.meshManager.getRendererSettings().frameDelayMsecProperty().bind(segmentMeshManager.getRendererSettings().frameDelayMsecProperty());
	this.meshManager.getRendererSettings().numElementsPerFrameProperty().bind(segmentMeshManager.getRendererSettings().numElementsPerFrameProperty());
	this.meshManager.getRendererSettings().sceneUpdateDelayMsecProperty().bind(segmentMeshManager.getRendererSettings().sceneUpdateDelayMsecProperty());

	thresholded.getThreshold().minValue().addListener((obs, oldv, newv) -> {
		getMeshFor.invalidateAll();
		refreshMeshes();
	});
	thresholded.getThreshold().maxValue().addListener((obs, oldv, newv) -> {
		getMeshFor.invalidateAll();
		refreshMeshes();
	});

	fragmentsInSelectedSegments.addListener(obs -> refreshMeshes());
}
 
Example 13
Source File: GenericViewArrow.java    From latexdraw with GNU General Public License v3.0 4 votes vote down vote up
default ObjectBinding<Color> createLineOrShadColBinding(final boolean isShadow) {
	if(isShadow) {
		return Bindings.createObjectBinding(() -> getArrow().getShape().getShadowCol().toJFX(), getArrow().getShape().shadowColProperty());
	}
	return Bindings.createObjectBinding(() -> getArrow().getShape().getLineColour().toJFX(), getArrow().getShape().lineColourProperty());
}
 
Example 14
Source File: GenericViewArrow.java    From latexdraw with GNU General Public License v3.0 4 votes vote down vote up
default ObjectBinding<Color> createFillOrShadColBinding(final boolean isShadow) {
	if(isShadow) {
		return Bindings.createObjectBinding(() -> getArrow().getShape().getShadowCol().toJFX(), getArrow().getShape().shadowColProperty());
	}
	return Bindings.createObjectBinding(() -> getArrow().getShape().getFillingCol().toJFX(), getArrow().getShape().fillingColProperty());
}
 
Example 15
Source File: ObjectBindings.java    From phoenicis with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Maps a {@link ObservableValue<I>} object to a {@link ObjectBinding<O>} by applying the given converter function.
 * In case the input value is empty, i.e. contains <code>null</code>, the given default value is used
 *
 * @param property The input value
 * @param converter The converter function
 * @param defaultValue The default value in case the input value is empty
 * @param <I> The type of the input value
 * @param <O> The type of the output value
 * @return A {@link ObjectBinding} containing the converted value
 */
public static <I, O> ObjectBinding<O> map(ObservableValue<I> property, Function<I, O> converter, O defaultValue) {
    return Bindings.createObjectBinding(
            () -> Optional.ofNullable(property.getValue()).map(converter).orElse(defaultValue), property);
}