@Override public void start(Stage stage) throws Exception { VBox root = new VBox(); Label label = new Label(""); // Turn Observable into Binding Binding<String> binding = Observable.interval(1, TimeUnit.SECONDS) .map(i -> i.toString()) .observeOn(JavaFxScheduler.platform()) .to(JavaFxObserver::toBinding); //Bind Label to Binding label.textProperty().bind(binding); root.setMinSize(200, 100); root.getChildren().addAll(label); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); }
@Override public void start(Stage stage) throws Exception { VBox root = new VBox(); Label label = new Label(""); // Observable with second timer Observable<String> seconds = Observable.interval(1, TimeUnit.SECONDS) .map(i -> i.toString()) .observeOn(JavaFxScheduler.platform()); // Turn Observable into Binding Binding<String> binding = JavaFxObserver.toBinding(seconds); //Bind Label to Binding label.textProperty().bind(binding); root.setMinSize(200, 100); root.getChildren().addAll(label); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); }
public StyledTableCell(TableColumn<LogEntry, String> column, Search search) { text = new SearchableLabel(search); text.fontProperty().bind(fontProperty()); setGraphic(text); setText(null); // this is usually called only once (when this cell is attached to a row) EasyBind.subscribe(tableRowProperty(), row -> { if (row == null) { return; } // bind the text for the foreground //noinspection unchecked Binding<Style> colorizedLogStyle = getOrCreateStyleBinding(row, colorizer); text.normalStyleProperty().bind(colorizedLogStyle); // apply the style to the cell for the background EasyBind.subscribe(colorizedLogStyle, s -> s.bindNode(this)); }); }
/** * Binds the filtered logs list predicate, the current filter, and the filter text field together. */ private void configureFiltering() { Callable<Predicate<LogEntry>> createFilter = () -> { try { filterField.pseudoClassStateChanged(Css.INVALID, false); if (filterField.getText().isEmpty()) { return log -> true; } int flags = caseSensitiveFilterCheckbox.isSelected() ? 0 : Pattern.CASE_INSENSITIVE; return Filter.findInRawLog(filterField.getText(), flags); } catch (PatternSyntaxException e) { filterField.pseudoClassStateChanged(Css.INVALID, true); return log -> false; } }; Binding<Predicate<LogEntry>> filterBinding = Bindings.createObjectBinding(createFilter, filterField.textProperty(), caseSensitiveFilterCheckbox.selectedProperty()); filterField.setText(""); UIUtils.makeClearable(filterField); filteredLogs.predicateProperty().bind(filterBinding); }
@Override public void initialize(URL location, ResourceBundle resources) { UIUtils.makeClearable(searchTextField); BooleanBinding disableMatchBrowsing = Bindings.createBooleanBinding(matchRows::isEmpty, matchRows); nextButton.disableProperty().bind(disableMatchBrowsing); previousButton.disableProperty().bind(disableMatchBrowsing); // TODO regex mode feature regexCheckBox.setDisable(true); search.textProperty().bind(searchTextField.textProperty()); search.matchCaseProperty().bind(matchCaseCheckBox.selectedProperty()); search.regexModeProperty().bind(regexCheckBox.selectedProperty()); Binding<Integer> matchRowsCount = Bindings.createObjectBinding(matchRows::size, matchRows); Binding<Integer> currentMatchRowIndexOneBased = Bindings.createObjectBinding(() -> { return currentMatchRowIndex.get() == null ? 0 : currentMatchRowIndex.get() + 1; }, currentMatchRowIndex); matchNavigationLabel.currentCountProperty().bind(currentMatchRowIndexOneBased); matchNavigationLabel.totalCountProperty().bind(matchRowsCount); matchNavigationLabel.visibleProperty().bind(currentMatchRowIndex.isNotNull()); }
@Test public void testSimpleMatchBinding() { Matcher<Integer> matcher = i -> i > 5; Property<Integer> intProp = new SimpleObjectProperty<>(2); Binding<Boolean> matches = matcher.matches(intProp); Assert.assertFalse(matches.getValue()); intProp.setValue(6); Assert.assertFalse(matches.isValid()); Assert.assertTrue(matches.getValue()); intProp.setValue(3); Assert.assertFalse(matches.isValid()); Assert.assertFalse(matches.getValue()); }
@SuppressWarnings("all") private SelectBindingHelper(Binding<?> binding, ObservableValue<?> firstProperty, String... steps) { if (firstProperty == null) { throw new NullPointerException("Must specify the root"); } if (steps == null) { steps = new String[0]; } this.binding = binding; final int n = steps.length; for (int i = 0; i < n; i++) { if (steps[i] == null) { throw new NullPointerException("all steps must be specified"); } } this.observer = new WeakInvalidationListener(this); this.propertyNames = new String[n]; System.arraycopy(steps, 0, this.propertyNames, 0, n); this.propRefs = new PropertyReference<?>[n]; this.properties = new ObservableValue<?>[n + 1]; this.properties[0] = firstProperty; this.properties[0].addListener(this.observer); }
/** * @param <A> the type of the argument * @param <Obs> the type of the observable * @param <R> the type of the return value */ @SuppressWarnings("unchecked") private static <A extends Number, Obs extends ObservableNumberValue, R extends Number> void testBinding(Function<Obs, Binding<R>> bindingFunction, Function<A, R> mathFunction, A... args) { if (args.length == 0) { throw new IllegalArgumentException("No args to verify!"); } Property base = createProperty(args[0]); final Binding<R> binding = bindingFunction.apply((Obs) base); for (A arg : args) { base.setValue(arg); R expectedResult = mathFunction.apply(arg); assertThat(binding).hasValue(expectedResult); } }
@SuppressWarnings("unchecked") static <A1 extends Number, A2 extends Number, Obs1 extends ObservableNumberValue, Obs2 extends ObservableNumberValue, R extends Number> void testTwoArgBinding1(BiFunction<Obs1, Obs2, Binding<R>> bindingFunction, BiFunction<A1, A2, R> mathFunction, Args<A1, A2>... args) { if (args.length == 0) { throw new IllegalArgumentException("No args to verify!"); } Property arg1 = createProperty(args[0].getFirst()); Property arg2 = createProperty(args[0].getSecond()); final Binding<R> binding = bindingFunction.apply((Obs1) arg1, (Obs2) arg2); for (Args<A1, A2> arg : args) { arg1.setValue(arg.getFirst()); arg2.setValue(arg.getSecond()); R expectedResult = mathFunction.apply(arg.getFirst(), arg.getSecond()); assertThat(binding).hasValue(expectedResult); } }
@SuppressWarnings("unchecked") static <A1 extends Number, A2 extends Number, Obs extends ObservableNumberValue, R extends Number> void testTwoArgBinding2(BiFunction<A1, Obs, Binding<R>> bindingFunction, BiFunction<A1, A2, R> mathFunction, Args<A1, A2>... args) { if (args.length == 0) { throw new IllegalArgumentException("No args to verify!"); } Property second = createProperty(args[0].getSecond()); for (Args<A1, A2> arg : args) { second.setValue(arg.getSecond()); final Binding<R> binding = bindingFunction.apply(arg.getFirst(), (Obs) second); R expectedResult = mathFunction.apply(arg.getFirst(), arg.getSecond()); assertThat(binding).hasValue(expectedResult); } }
@SuppressWarnings("unchecked") static <A1 extends Number, A2 extends Number, Obs extends ObservableNumberValue, R extends Number> void testTwoArgBinding3(BiFunction<Obs, A2, Binding<R>> bindingFunction, BiFunction<A1, A2, R> mathFunction, Args<A1, A2>... args) { if (args.length == 0) { throw new IllegalArgumentException("No args to verify!"); } Property first = createProperty(args[0].getFirst()); for (Args<A1, A2> arg : args) { first.setValue(arg.getFirst()); final Binding<R> binding = bindingFunction.apply((Obs) first, arg.getSecond()); R expectedResult = mathFunction.apply(arg.getFirst(), arg.getSecond()); assertThat(binding).hasValue(expectedResult); } }
/** * Binds {@code firstProperty} to {@code secondProperty}, using a conversion function to map * values of type {@code U} to {@code T} so the first property can be bound. * * @param firstProperty the property to bind * @param secondProperty the property to bind to * @param u2tConverter the conversion function */ public static <T, U> void bindWithConverter( Property<T> firstProperty, Property<U> secondProperty, Function<U, T> u2tConverter) { Binding<T> binding = EasyBind.monadic(secondProperty).map(u2tConverter); bindings.put(firstProperty, binding); firstProperty.bind(binding); }
public final Binding<Image> createPosterImageBinding() { return Bindings.createObjectBinding(() -> { return Optional.ofNullable(getPosterFileName()). map(s -> new Image(Database.class.getResource(s).toExternalForm())). orElse(null); }, posterFileNameProperty()); }
public final Binding<Image> createBackgroundImageBinding() { return Bindings.createObjectBinding(() -> { return Optional.ofNullable(getBackgroundFileName()). map(s -> new Image(Database.class.getResource(s).toExternalForm())). orElse(null); }, backgroundFileNameProperty()); }
public static void main(String[] args) { ObjectProperty<LocalDateTime> dp = new SimpleObjectProperty<>(LocalDateTime.now()); ObjectProperty<Instant> ip = new SimpleObjectProperty<>(); Binding<Instant> ib = Bindings.createObjectBinding( () -> dp.get().toInstant(OffsetDateTime.now().getOffset()), dp); ip.bind(ib); // Binding<LocalDateTime> db = Bindings.createObjectBinding( // () -> ip.get().atZone(ZoneId.systemDefault()).toLocalDateTime(), // ip); // dp.bind(db); dp.addListener((obs, ov, nv) -> System.out.println(dp.get())); ip.addListener((obs, ov, nv) -> System.out.println(ip.get())); dp.setValue(LocalDateTime.of(2000, 9, 22, 9, 16, 0)); dp.setValue(LocalDateTime.of(1968, 12, 25, 8, 0, 0)); dp.setValue(LocalDateTime.of(2002, 7, 27, 3, 30, 0)); // // ip.setValue(Instant.EPOCH); // ip.setValue(Instant.MAX); // ip.setValue(Instant.MIN); }
private void bindRule(Rule<T, U, M> rule) { bind(rule.resultProperty()); Binding<Boolean> currentBinding = EasyBind.select(rule.matcherProperty()).selectObject(m -> m.matches(input)); ruleMatchBindings.put(rule, currentBinding); bind(currentBinding); }
private static Binding<Style> getOrCreateStyleBinding(TableRow<LogEntry> row, ObservableValue<Colorizer> colorizer) { @SuppressWarnings("unchecked") Binding<Style> colorizedLogStyle = (Binding<Style>) row.getProperties().get(STYLE_BINDING_KEY); if (colorizedLogStyle == null) { ObservableValue<LogEntry> observableLogValue = row.itemProperty(); colorizedLogStyle = RuleSet.outputFor(colorizer, observableLogValue, Style.DEFAULT); row.getProperties().put(STYLE_BINDING_KEY, colorizedLogStyle); } return colorizedLogStyle; }
private Binding<Tooltip> createTooltipBinding() { Tooltip tooltip = new Tooltip(); tooltip.textProperty().bind(description); BooleanBinding descriptionIsNull = description.isNull(); Callable<Tooltip> tooltipCallable = () -> { if (descriptionIsNull.get()) { // no tooltip when no description return null; } return tooltip; }; return Bindings.createObjectBinding(tooltipCallable, descriptionIsNull); }
private Binding<Predicate<LogEntry>> createLogSearcherBinding(Binding<Predicate<String>> textMatcherBinding) { Callable<Predicate<LogEntry>> createLogMatcher = () -> { return createLogEntryMatcher(textMatcherBinding.getValue(), columnDefinitions.getValue()); }; return Bindings.createObjectBinding(createLogMatcher, textMatcherBinding, columnDefinitions); }
private static void bindActivableColorPicker(@NotNull Property<Color> colorProperty, @NotNull ColorPicker picker, @NotNull CheckBox checkbox) { // initial values Color currentValue = colorProperty.getValue(); picker.setValue(currentValue == null ? Color.WHITE : currentValue); checkbox.setSelected(currentValue != null); // binding Callable<Color> getColor = () -> checkbox.isSelected() ? picker.getValue() : null; Binding<Color> colorBinding = Bindings.createObjectBinding(getColor, checkbox.selectedProperty(), picker.valueProperty()); colorProperty.bind(colorBinding); }
@Test public void testSimpleRuleSetBinding() { RuleSet<Integer, String, Matcher<Integer>, Rule<Integer, String, Matcher<Integer>>> ruleSet = new RuleSet<>(); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 5, "Very small")); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 10, "Small")); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 15, "Large")); ruleSet.getRules().add(new Rule<>(i1 -> i1 != null && i1 < 20, "Very large")); Property<Integer> intProp = new SimpleObjectProperty<>(null); Binding<String> resultBinding = ruleSet.outputFor(intProp, "default"); Assert.assertEquals("Should return the default", "default", resultBinding.getValue()); intProp.setValue(3); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match 1st rule", "Very small", resultBinding.getValue()); intProp.setValue(8); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match 2nd rule", "Small", resultBinding.getValue()); intProp.setValue(17); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match 4th rule", "Very large", resultBinding.getValue()); intProp.setValue(50); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should return the default", "default", resultBinding.getValue()); }
@Test public void testChangingRules() { RuleSet<Integer, String, Matcher<Integer>, Rule<Integer, String, Matcher<Integer>>> ruleSet = new RuleSet<>(); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 5, "Very small")); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 10, "Small")); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 15, "Large")); Rule<Integer, String, Matcher<Integer>> veryLargeRule = new Rule<>(i -> i != null && i < 20, "Very large"); ruleSet.getRules().add(veryLargeRule); Property<Integer> intProp = new SimpleObjectProperty<>(null); Binding<String> resultBinding = ruleSet.outputFor(intProp, "default"); intProp.setValue(50); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should return the default", "default", resultBinding.getValue()); ruleSet.getRules().add(new Rule<>(i -> i != null && i < 100, "Extra large")); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match new rule", "Extra large", resultBinding.getValue()); intProp.setValue(17); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match 4th rule", "Very large", resultBinding.getValue()); ruleSet.getRules().remove(veryLargeRule); Assert.assertFalse(resultBinding.isValid()); Assert.assertEquals("Should match 5th rule", "Extra large", resultBinding.getValue()); }
public Binding<Number> createNumericMeasurement(final PathObject pathObject, final String column) { MeasurementBuilder<?> builder = builderMap.get(column); if (builder == null) return new ObservableMeasurement(pathObject, column); else if (builder instanceof NumericMeasurementBuilder) return ((NumericMeasurementBuilder)builder).createMeasurement(pathObject); else throw new IllegalArgumentException(column + " does not represent a numeric measurement!"); }
public Binding<String> createStringMeasurement(final PathObject pathObject, final String column) { MeasurementBuilder<?> builder = builderMap.get(column); if (builder instanceof StringMeasurementBuilder) return ((StringMeasurementBuilder)builder).createMeasurement(pathObject); else throw new IllegalArgumentException(column + " does not represent a String measurement!"); }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { // Only return density measurements for annotations if (pathObject.isAnnotation() || (pathObject.isTMACore() && pathObject.getChildObjects().size() == 1)) return new ClassDensityMeasurementPerMM(server, pathObject, pathClass); return Bindings.createDoubleBinding(() -> Double.NaN); }
@Override public Binding<String> createMeasurement(final PathObject pathObject) { return new StringBinding() { @Override protected String computeValue() { return getMeasurementValue(pathObject); } }; }
@Override public Binding<Number> createMeasurement(PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { return getCentroid(pathObject.getROI()); } }; }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { ROI roi = pathObject.getROI(); if (!(roi instanceof PathArea)) return Double.NaN; if (hasPixelSizeMicrons()) return ((PathArea)roi).getScaledArea(pixelWidthMicrons(), pixelHeightMicrons()); return ((PathArea)roi).getArea(); } }; }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { ROI roi = pathObject.getROI(); if (!(roi instanceof PathArea)) return Double.NaN; if (hasPixelSizeMicrons()) return ((PathArea)roi).getScaledPerimeter(pixelWidthMicrons(), pixelHeightMicrons()); return ((PathArea)roi).getPerimeter(); } }; }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { ROI roi = pathObject.getROI(); List<Point2> points; if (roi instanceof PolygonROI) points = ((PolygonROI)roi).getPolygonPoints(); else if (roi instanceof AreaROI) points = ((AreaROI)roi).getPolygonPoints(); else return Double.NaN; double xScale = hasPixelSizeMicrons() ? pixelWidthMicrons() : 1; double yScale = hasPixelSizeMicrons() ? pixelHeightMicrons() : 1; double maxLengthSq = 0; for (int i = 0; i < points.size(); i++) { Point2 pi = points.get(i); for (int j = i+1; j < points.size(); j++) { Point2 pj = points.get(j); double dx = (pi.getX() - pj.getX()) * xScale; double dy = (pi.getY() - pj.getY()) * yScale; maxLengthSq = Math.max(maxLengthSq, dx*dx + dy*dy); } } return Math.sqrt(maxLengthSq); } }; }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { ROI roi = pathObject.getROI(); if (!(roi instanceof PathLine)) return Double.NaN; if (hasPixelSizeMicrons()) return ((PathLine)roi).getScaledLength(pixelWidthMicrons(), pixelHeightMicrons()); return ((PathLine)roi).getLength(); } }; }
@Override public Binding<Number> createMeasurement(final PathObject pathObject) { return new DoubleBinding() { @Override protected double computeValue() { ROI roi = pathObject.getROI(); if (!(roi instanceof PathPoints)) return Double.NaN; return ((PathPoints)roi).getNPoints(); } }; }
public static void updateBindings() { for (Binding<Boolean> b : bindings_) { b.invalidate(); } }
@Test public void testGenericBinding(){ Binding<Float> actual = Bindings.createObjectBinding(() -> 20f); assertThat(actual).hasValue(20f); assertThat(actual).hasSameValue(actual); }
@Test public void testGenericBinding(){ Binding<Integer> actual = Bindings.createObjectBinding(() -> 20); assertThat(actual).hasValue(20); assertThat(actual).hasSameValue(actual); }
@Test public void testGenericBinding(){ Binding<Long> actual = Bindings.createObjectBinding(() -> 20l); assertThat(actual).hasValue(20l); assertThat(actual).hasSameValue(actual); }
@Test public void testGenericBinding(){ Binding<TestPerson> actual = Bindings.createObjectBinding(()->person); assertThat(actual).hasValue(person); assertThat(actual).hasSameValue(actual); }
@Test public void testGenericBinding(){ Binding<Double> actual = Bindings.createObjectBinding(()->20.2); assertThat(actual).hasValue(20.2); assertThat(actual).hasSameValue(actual); }
@Test public void testGenericBinding(){ Binding<String> actual = Bindings.createObjectBinding(()-> "test"); assertThat(actual).hasValue("test"); assertThat(actual).hasSameValue(actual); }
@Test public void should_fail_if_actual_has_a_value_of_null(){ try{ Binding<String> actual = Bindings.createObjectBinding(()->null); new BindingAssertions<>(actual).hasNotNullValue(); fail("Should throw an AssertionError"); }catch(AssertionError error){ assertThat(error).hasMessageContaining("Expected binding to not have a value of null"); } }