工作表,请参见下面的示例。
但是:通常启用管理应该由 bean 本身处理(而不是在运行中处理)——在一个设计良好的分离世界中,只有 bean 本身应该拥有所有必要的知识。
一些代码:
final Person person = new Person();
// enablement binding with ad-hoc decision in view
Action action = new AbstractAction("Add year") {
public void actionPerformed(ActionEvent e) {
person.setAge(person.getAge() + 1);
}
};
JButton button = new JButton(action);
Binding enable = Bindings.createAutoBinding(UpdateStrategy.READ,
person, ELProperty.create("${age < 6}"),
button, BeanProperty.create("enabled"));
enable.bind();
// enablement binding to a bean property
Action increment = new AbstractAction("Increment year") {
public void actionPerformed(ActionEvent e) {
person.incrementAge();
}
};
JButton incrementButton = new JButton(increment);
Binding incrementable = Bindings.createAutoBinding(UpdateStrategy.READ,
person, BeanProperty.create("incrementable"),
incrementButton, BeanProperty.create("enabled"));
incrementable.bind();
JSlider age = new JSlider(0, 10, 0);
Binding binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
person, BeanProperty.create("age"),
age, BeanProperty.create("value"));
binding.bind();
// the bean
public static class Person extends AbstractBean {
private int age;
private int max;
public Person() {
max = 6;
}
public void incrementAge() {
setAge(getAge() + 1);
}
public boolean isIncrementable() {
return getAge() < max;
}
public void setAge(int age) {
boolean incrementable = isIncrementable();
int old = getAge();
this.age = age;
firePropertyChange("age", old, getAge());
firePropertyChange("incrementable", incrementable, isIncrementable());
}
public int getAge() {
return age;
}
}