有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建基于整数的布尔属性/绑定?

我想创建一个通过int保存布尔信息的类:如果其值大于0,则布尔值为true,否则为false

这是一个封装此行为的类:

public class CumulativeBoolean {

    private int cumulative = 0;

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

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

我想从这个设计中创建一个JavaFX类,它允许绑定和监听。我研究了扩展BooleanBindingBooleanPropertyBase,它们都将private boolean value作为其值,而我想要的是int

这就是我为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;
    }
}

然而,我不认为BooleanBinding的想法是为了支持set功能,还有一个问题是在值被绑定时设置值

另一方面BooleanPropertyBase不允许我在更新时失效,因为它的markInvalid方法和valid字段是私有的

我怎样才能做到这一点


共 (1) 个答案

  1. # 1 楼答案

    如果要使用JavaFX的绑定功能,必须使用ObservalEvalue(例如SimpleIntegerProperty)

    下面的代码显示了一个如何实现它的快速示例:

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

    如果不想在类中使用整数的ObservalEvalue,另一个选项是在设置int时更新Boolean属性:

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

    每次调用set方法后:

    fakeBinding.set(value >= 0);
    

    编辑:看起来MBec比我快:p