Skip to content

Properties

Mose edited this page May 12, 2023 · 2 revisions

Basic usage

Typically to write a field value, you would do something like this.

private boolean foo;

however the main issue with this is if your wanting to know when this value changes, you need to create a event and then change it. This is fine if its only being changed in one place, but when it comes to multiple locations, it can get a little inconstant.

To fix this, we can use a property in its place, for example

private final Property<Boolean, Boolean> foo = new WritePropertyImpl<>(false);

A property is a great tool when building a public API as changing any value that is a property will have a event for anyone to hook into.

The first generic is the value type, with the second being the display value. The display side of things is for mapping the actual value to a read only value to prevent users from getting around calling events

Events

Registering a event is based on Java's traditional events.

Property<Boolean, Boolean> property;
property.registerValueChangeEvent(new PropertyChangeEvent<>() {

    @Override
    public void handle(Property<Boolean, ?> targetProperty, Boolean currentValue, ValueSetType type, Boolean newValue){
        System.out.println("Value changed");
    }
});

This can be changed to a traditional lamda too

Property<Boolean, Boolean> property;
property.registerValueChangeEvent((targetProperty, currentValue, type, newValue) -> System.out.println("Value changed"));

Binding

Sometimes all you care about is a small part and just want to register events for when that small part changes. Thankfully you can. In this example we take a Collection property and bind a property of boolean for if the collection is empty.

CollectionProperty<Integer, Collection<Integer>> property;
Property<Boolean, Boolean> isEmptyProperty = new ReadOnlyPropertyImpl();
isEmptyProperty.bindTo(property, collection -> collection.isEmpty()); 

Clone this wiki locally