本文介绍了JavaFX:如何在列表中绑定多个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类SimpleElement,它有一个权重字段,第二个类有一个SimpleElement列表,一个权重字段取决于列表中包含的所有其他SimpleElement的权重之和.有人知道如何通过绑定来做到这一点吗?

I have a class SimpleElement which has a weight field and the second one has a list of SimpleElement and a weight field which depends on the sum of weight of all other SimpleElements containing in the list. Any one has any idea how to do that by binding?

我的代码:

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;

public class SimpleElement {

    IntegerProperty weight;

    public SimpleElement() {
        weight = new SimpleIntegerProperty();
    }

    public int getWeight() {
        return weight.get();
    }

    public void setWeight(int weight) {
        this.weight.set(weight);
    }

    public IntegerProperty weightProperty() {
        return weight;
    }
}

import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;

public class RootElement {

    List<SimpleElement> elements;
    IntegerProperty weight;

    public RootElement() {
        elements = new ArrayList<>();
        weight = new SimpleIntegerProperty();
    }

    public void addelements(SimpleElement element) {
        elements.add(element);
    }
}

推荐答案

可以重写RootElement类以创建对每个SimpleElement的绑定,并将它们加起来:

The RootElement class can be rewritten to create a binding to each SimpleElement, adding them up:

public class RootElement {
    List<SimpleElement> elements;
    IntegerProperty weight;
    NumberBinding binding;

    public RootElement() {
        elements = new ArrayList<>();
        weight = new SimpleIntegerProperty();
    }

    public void addelements(SimpleElement element) {
        elements.add(element);

        if (binding == null) {
            binding = element.weightProperty().add(0);
        } else {
            binding = binding.add(element.weightProperty());
        }

        weight.bind(binding);
    }

    public Integer getWeight() {
        return weight.get();
    }

    public ReadOnlyIntegerProperty weightProperty() {
        return weight;
    }
}

用法示例:

public static void main(String[] args) {
    SimpleElement se1 = new SimpleElement();
    SimpleElement se2 = new SimpleElement();
    SimpleElement se3 = new SimpleElement();
    RootElement root = new RootElement();

    root.addelements(se1);
    root.addelements(se2);
    root.addelements(se3);

    root.weightProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            System.out.println(newValue);
        }
    });

    se1.setWeight(3);
    se2.setWeight(2);
    se1.setWeight(4);
}

执行上面的代码会产生:

The execution of the code above produces:

3

5

6

这篇关于JavaFX:如何在列表中绑定多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:06