Javafx贪婪的约束

时间:2017-07-02 19:55:56

标签: javafx

根据下面的示例代码,Java FX Bindings默认情况下似乎不贪婪。

  
assertEquals(2,calledEffect); 

不起作用 但

  
assertEquals(2,keepBinding.get())

确实

我怎样才能确保Binding自动激活 - 获得贪婪行为?

  
long calledEffect=0;
private LongBinding keepBinding;
public long callMe(long value) {
  calledEffect=value+1;
  return calledEffect;
}

@Test
public void testBinding() {
  SimpleLongProperty lp = new SimpleLongProperty(); 
  lp.setValue(4711);
  keepBinding=Bindings.createLongBinding(()->callMe(lp.get()),lp);
  lp.setValue(1);
  //assertEquals(2,calledEffect);
  assertEquals(2,keepBinding.get());
}

1 个答案:

答案 0 :(得分:1)

只有在需要获取其值时才会计算绑定。如果要在值更改时调用代码,请使用更改侦听器:

lp.addListener((obs, oldValue, newValue) -> callMe(newValue));

然后您的代码需要更改为:

long calledEffect=0;
private LongBinding keepBinding;
public long callMe(Number newValue) {
  calledEffect=newValue.longValue()+1;
  return calledEffect;
}

@Test
public void testBinding() {
  SimpleLongProperty lp = new SimpleLongProperty(); 
  lp.setValue(4711);
  keepBinding=Bindings.createLongBinding(()->callMe(lp.get()),lp);
  lp.addListener((obs, oldValue, newValue) -> callMe(newValue));
  lp.setValue(1);
  assertEquals(2,calledEffect);
  assertEquals(2,keepBinding.get());
}