重载JavaFX绑定

时间:2018-08-10 00:20:51

标签: javafx binding override overloading subclassing

我正在绑定两个标签,通过对Bindings.when()的一系列嵌套调用来计算第二个标签的值。由于我连续3次对3个相似的标签执行相同的操作,是否有办法通过重载Bindings方法或IntegerBinding方法之一来简化此代码?

private IntegerProperty ipStrength, ipAgility, ipIntelligence;
private IntegerProperty ipStBonus, ipAgBonus, ipInBonus;


public RolePlayingCharacter() {

    ...

    ipStBonus.bind(Bindings.when(ipStrength.lessThan(5))
            .then(-1)
            .otherwise(Bindings.when(ipStrength.lessThan(9))
                    .then(0)
                    .otherwise(Bindings.when(ipStrength.lessThan(11))
                            .then(1)
                            .otherwise(2))));

    ipAgBonus.bind(Bindings.when(ipAgility.lessThan(5))
            .then(-1)
            .otherwise(Bindings.when(ipAgility.lessThan(9))
                    .then(0)
                    .otherwise(Bindings.when(ipAgility.lessThan(11))
                            .then(1)
                            .otherwise(2))));

    ipInBonus.bind(Bindings.when(ipIntelligence.lessThan(5))
            .then(-1)
            .otherwise(Bindings.when(ipIntelligence.lessThan(9))
                    .then(0)
                    .otherwise(Bindings.when(ipIntelligence.lessThan(11))
                            .then(1)
                            .otherwise(2))));

    ...

我发现我可以重写Class IntegerBinding的computeValue方法,但这似乎无济于事,因为无论如何我必须做3次某些事情,每个标签一次:

    IntegerBinding ibStatBonus = new IntegerBinding() {
        {
            super.bind(ipStrength);
        }

        @Override
        protected int computeValue() {
            int iStatValue = ipStrength.get();
            if (iStatValue < 5) {
                return -1;
            } else if (iStatValue < 9) {
                return 0;
            } else if (iStatValue < 11) {
                return 1;
            } else {
                return 2;
            }
        }
    };

我希望能够做一些简单的事情,例如:

    ipStBonus.bind(ipStrength.calculateStatBonus());
    ipAgBonus.bind(ipAgility.calculateStatBonus());
    ipInBonus.bind(ipIntelligence.calculateStatBonus());

我该如何实施?如何使caclulateStatBonus方法成为IntegerProperty可用方法列表的一部分?

1 个答案:

答案 0 :(得分:1)

总是可以为此创建一个辅助方法:

public static IntegerBinding createStatBonusBinding(final IntegerProperty source) {
    return Bindings.createIntegerBinding(() -> {
        int value = source.get();
        if (value < 5) {
            return -1;
        }
        if (value < 9) {
            return 0;
        }
        if (value < 11) {
            return 1;
        }
        return 2;
    }, source);
}
ipStBonus.bind(createStatBonusBinding(ipStrength));
ipAgBonus.bind(createStatBonusBinding(ipAgility));
ipInBonus.bind(createStatBonusBinding(ipIntelligence));