I got the following data model:
public class Player {
// enum to integer (count)
@Getter
private MapProperty<ResourceType, Integer> resourceCards = new SimpleMapProperty<>();
public void addResource(final ResourceType resourceType, final int amount) {
this.resourceCards.get().put(resourceType, this.resourceCards.get().get(resourceType) + amount);
}
}
public class Game {
@Getter
@Setter
private ObjectProperty<Player> currentPlayer = new SimpleObjectProperty<>();
}
Binding the map to a text property is quite easy:
final Label label = new Label();
label.textProperty().bind(EasyBind.select(game.getCurrentPlayer()).selectObject(player -> player.getResourceCards().asString()));
I would like to display the total amount of resource cards in the label.
Example:
Map: {Water=0, Gold=2, Lumber=5}
Label: 7
Map: {Water=0, Gold=0, Lumber=0}
Label: 0
How can I achieve this with JavaFX Bindings or/and EasyBind?
A
MapProperty<S, T>
can be used asObservableMap<S, T>
and gets notified of changes of the wrapped map. This means you can useBindings.createStringBinding
on the map:Note: Convention for the method name of the method returning the property object itself is using
<propertyName>Property
. In case of yourGame
'scurrentPlayer
property this would becurrentPlayerProperty()
instead ofgetCurrentPlayer()
andresourceCardsProperty()
instead ofgetResourceCards()
. I used the method names includingget
in the above code.Furthermore using a
MapProperty
is unnecessary unless you're planing to replace the whole map instead of simply modifying theMap
's contents. You could simply use a readonly property of typeObservableMap
in this case.