• Stars
    star
    151
  • Rank 246,057 (Top 5 %)
  • Language
    Java
  • License
    BSD 2-Clause "Sim...
  • Created almost 11 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Custom JavaFX bindings made easy with lambdas.

EasyBind

EasyBind leverages lambdas to reduce boilerplate when creating custom bindings, provides a type-safe alternative to Bindings.select* methods (inspired by Anton Nashatyrev's feature request, planned for JavaFX 9) and adds monadic operations to ObservableValue.

Static methods

map

Creates a binding whose value is a mapping of some observable value.

ObservableStringValue str = ...;
Binding<Integer> strLen = EasyBind.map(str, String::length);

Compare to plain JavaFX:

ObservableStringValue str = ...;
IntegerBinding strLen = Bindings.createIntegerBinding(() -> str.get().length(), str);

The difference is subtle, but important: In the latter version, str is repeated twice — once in the function to compute binding's value and once as binding's dependency. This opens the possibility that a wrong dependency is specified by mistake.

combine

Creates a binding whose value is a combination of two or more (currently up to six) observable values.

ObservableStringValue str = ...;
ObservableValue<Integer> start = ...;
ObservableValue<Integer> end = ...;
Binding<String> subStr = EasyBind.combine(str, start, end, String::substring);

Compare to plain JavaFX:

ObservableStringValue str = ...;
ObservableIntegerValue start = ...;
ObservableIntegerValue end = ...;
StringBinding subStr = Bindings.createStringBinding(() -> str.get().substring(start.get(), end.get()), str, start, end);

Same difference as before — in the latter version, str, start and end are repeated twice, once in the function to compute binding's value and once as binding's dependencies, which opens the possibility of specifying wrong set of dependencies. Plus, the latter is getting less readable.

select

Type-safe alternative to Bindings.select* methods. The following example is borrowed from RT-35923.

Binding<Boolean> bb = EasyBind.select(control.sceneProperty()) 
        .select(s -> s.windowProperty()) 
        .selectObject(w -> w.showingProperty());

Compare to plain JavaFX:

BooleanBinding bb = Bindings.selectBoolean(control.sceneProperty(), "window", "isShowing");

The latter version is not type-safe, which means it may cause runtime errors.

map list

Returns a mapped view of an ObservableList.

ObservableList<String> tabIds = EasyBind.map(tabPane.getTabs(), Tab::getId);

In the above example, tabIds is updated as tabs are added and removed from tabPane.

An equivalent feature has been requested in JDK-8091967 and is scheduled for a future JavaFX release.

combine list

Turns an observable list of observable values into a single observable value. The resulting observable value is updated when elements are added or removed to or from the list, as well as when element values change.

Property<Integer> a = new SimpleObjectProperty<>(5);
Property<Integer> b = new SimpleObjectProperty<>(10);
ObservableList<Property<Integer>> list = FXCollections.observableArrayList();

Binding<Integer> sum = EasyBind.combine(
        list,
        stream -> stream.reduce((a, b) -> a + b).orElse(0));

assert sum.getValue() == 0;

// sum responds to element additions
list.add(a);
list.add(b);
assert sum.getValue() == 15;

// sum responds to element value changes
a.setValue(20);
assert sum.getValue() == 30;

// sum responds to element removals
list.remove(a);
assert sum.getValue() == 10;

You don't usually have an observable list of observable values, but you often have an observable list of something that contains an observable value. In that case, use the above map methods to get an observable list of observable values, as in the example below.

Example: Disable "Save All" button on no unsaved changes

Assume a tab pane that contains a text editor in every tab. The set of open tabs (i.e. open files) is changing. Let's further assume we use a custom Tab subclass EditorTab that has a boolean savedProperty() that indicates whether changes in its editor have been saved.

Task: Keep the "Save All" button disabled when there are no unsaved changes in any of the editors.

ObservableList<ObservableValue<Boolean>> individualTabsSaved =
        EasyBind.map(tabPane.getTabs(), t -> ((EditorTab) t).savedProperty());

ObservableValue<Boolean> allTabsSaved = EasyBind.combine(
        individualTabsSaved,
        stream -> stream.allMatch(saved -> saved));

Button saveAllButton = new Button(...);
saveAllButton.disableProperty().bind(allTabsSaved);

bind list

Occasionally one needs to synchronize the contents of an (observable) list with another observable list. If that is your case, listBind is your friend:

ObservableList<T> sourceList = ...;
List<T> targetList = ...;
EasyBind.listBind(targetList, sourceList);

subscribe to values

Often one wants to execute some code for each value of an ObservableValue, that is for the current value and each new value. This typically results in code like this:

this.doSomething(observable.getValue());
observable.addListener((obs, oldValue, newValue) -> this.doSomething(newValue));

This can be expressed more concisely using the subscribe helper method:

EasyBind.subscribe(observable, this::doSomething);

conditional collection membership

EasyBind.includeWhen includes or excludes an element in/from a collection based on a boolean condition.

Say that you want to draw a graph and highlight an edge when the edge itself or either of its end vertices is hovered over. To achieve this, let's add .highlight CSS class to the edge node when either of the three is hovered over and remove it when none of them is hovered over:

BooleanBinding highlight = edge.hoverProperty()
        .or(v1.hoverProperty())
        .or(v2.hoverProperty());
EasyBind.includeWhen(edge.getStyleClass(), "highlight", highlight);
.highlight { -fx-stroke: green; }

Monadic observable values

MonadicObservableValue interface adds monadic operations to ObservableValue.

interface MonadicObservableValue<T> extends ObservableValue<T> {
    boolean isPresent();
    boolean isEmpty();
    void ifPresent(Consumer<? super T> f);
    T getOrThrow();
    T getOrElse(T other);
    Optional<T> getOpt();
    MonadicBinding<T> orElse(T other);
    MonadicBinding<T> orElse(ObservableValue<T> other);
    MonadicBinding<T> filter(Predicate<? super T> p);
    <U> MonadicBinding<U> map(Function<? super T, ? extends U> f);
    <U> MonadicBinding<U> flatMap(Function<? super T, ObservableValue<U>> f);
    <U> PropertyBinding<U> selectProperty(Function<? super T, Property<U>> f);
}

Read more about monadic operations in this blog post.

The last two methods, flatMap and selectProperty, let you select a nested ObservableValue or Property, respectively. The nested property can be bound, just like a normal property. Example:

DoubleProperty changingOpacity = ...;
Property<Number> currentTabContentOpacity = EasyBind.monadic(tabPane.selectionModelProperty())
        .flatMap(SelectionModel::selectedItemProperty)
        .flatMap(Tab::contentProperty)
        .selectProperty(Node::opacityProperty);
currentTabContentOpacity.bind(changingOpacity);

In this example, when you switch tabs, the old tab's content opacity is unbound and the new tab's content opacity is bound to changingOpacity.

Use EasyBind in your project

Stable release

Current stable release is 1.0.3.

Maven coordinates

Group ID Artifact ID Version
org.fxmisc.easybind easybind 1.0.3

Gradle example

dependencies {
    compile group: 'org.fxmisc.easybind', name: 'easybind', version: '1.0.3'
}

Sbt example

libraryDependencies += "org.fxmisc.easybind" % "easybind" % "1.0.3"

Manual download

Download the JAR file and place it on your classpath.

Snapshot releases

Snapshot releases are deployed to Sonatype snapshot repository.

Maven coordinates

Group ID Artifact ID Version
org.fxmisc.easybind easybind 1.0.4-SNAPSHOT

Gradle example

repositories {
    maven {
        url 'https://oss.sonatype.org/content/repositories/snapshots/' 
    }
}

dependencies {
    compile group: 'org.fxmisc.easybind', name: 'easybind', version: '1.0.4-SNAPSHOT'
}

Sbt example

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

libraryDependencies += "org.fxmisc.easybind" % "easybind" % "1.0.4-SNAPSHOT"

Manual download

Download the latest JAR file and place it on your classpath.

Links

Javadoc