groovy and javafx 2.2: MapChangeListener

javafx does have groovy support through groovyfx (or something like that). But here's another small way to help tame some of the large API base in javafx with some groovy help.

Take listening to a map. Since I store alot of resources in the Node's maps, I need to know whey are changing. Here's a simple class that helps you with detecting changes and firing off some closures:




/**
* Map change listener that takes closures. By default, it does nothing when a change occurs in the map.
* The closures are called with the tuple {@code (map, key, value-added/removed)}.
* @author Mr. Java
*
*/
class SimpleMapChangeListener implements MapChangeListener {

Closure added
Closure removed

public Closure getAdded() {
return added;
}


public Closure getRemoved() {
return removed;
}


public void setAdded(Closure added) {
this.added = added;
}


public void setRemoved(Closure removed) {
this.removed = removed;
}

public SimpleMapChangeListener(Closure added= {}, Closure removed={}) {
this.added = added
this.removed = removed
}


@Override
public void onChanged(Change arg0) {
if(arg0.wasAdded())
added?.call(arg0.map, arg0.key, arg0.valueAdded)
else
removed?.call(arg0.map, arg0.key, arg0.valueRemoved)
}
}
You can use this very simple by calling


yourNode.getProperties().addListener(new SimpleMapChangeListener(
{ m, k, v -> actionWhenValueAdded(v) },
{ m, k, v -> actionWhenValueRemoved(v) }))
or just supply them with named parameters or let the defaults kick-in.

Comments

Popular posts from this blog

quick note on scala.js, react hooks, monix, auth

zio environment and modules pattern: zio, scala.js, react, query management

user experience, scala.js, cats-effect, IO