Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a boolean property/binding whose value is based on an integer?

Tags:

java

javafx

I want to create a class which holds boolean information via an int: if its value is greater than 0 the boolean's value is true, otherwise false.

This is a class that encapsulates this behavior:

public class CumulativeBoolean {

    private int cumulative = 0;

    public boolean get() {
        return cumulative > 0;
    }

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
    }
}

I want to create a JavaFX class from this design that allows binding and listening. I looked at extending either BooleanBinding or BooleanPropertyBase, they both hold a private boolean value as their value while what I want is an int.

This is what I have for BooleanBinding:

public class CumulativeBooleanBinding extends BooleanBinding {

    private int cumulative = 0;

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
        invalidate();
    }

    @Override
    protected boolean computeValue() {
        return cumulative != 0;
    }
}

However, I don't think that the idea of BooleanBinding was to support a set functionality, and there is also the issue of setting the value while the value is bound.

BooleanPropertyBase, on the other hand, does not allow me to invalidate when updating since its markInvalid method and valid fields are private.

How could I achieve this?

like image 239
user1803551 Avatar asked Dec 11 '25 04:12

user1803551


1 Answers

If you want to use the binding-functionality of JavaFX, you have to use a ObservableValue (such as SimpleIntegerProperty).

The following code shows a quick example how to implement it:

SimpleIntegerProperty intProp = new SimpleIntegerProperty(0);
BooleanBinding binding = intProp.greaterThanOrEqualTo(0);

If you don't want to use an ObservableValue of Integer in your class, the other option is to update a BooleanProperty when setting your int:

SimpleBooleanProperty fakeBinding = new SimpleBooleanProperty(value >= 0);

and after every call to the set method:

fakeBinding.set(value >= 0);

EDIT: Seems like MBec was faster than me :p

like image 66
Felix Avatar answered Dec 13 '25 17:12

Felix