简体   繁体   English

如何在JavaFX中实现派生的只读属性/值?

[英]How to implement derived read-only properties/values in JavaFX?

Suppose I have an object, representing database table and it has property, denoting current selected row: 假设我有一个对象,表示数据库表,并且它具有属性,表示当前选定的行:

class MyTable {

   private IntegerProperty currentRow ...

   public IntegerProperty currentRowProperty() {
      return currentRow;
   }

   public int getCurrentRow() {
      return currentRow.get();
   }

   public void setCurrentRow(int newValue) {
      currentRow.setValue(newValue);
   }
}

Now I wish to have additional explicit read-only entity to denote, whether the row can be moved to previous (to bind to "previous" button). 现在,我希望有其他的显式只读实体来表示该行是否可以移至上一个(绑定到“上一个”按钮)。

If I implement it with Binding 如果我用绑定实现它

class MyTable {

   private BooleanBinding previousExist = currentRowProperty().greaterThan(0);

   public BooleanBinding previousExistBinding() {
      return previousExist;
   }

   public boolean isPreviousExist() {
      return previousExist.get();
   }
}

I will violate JavaFX property pattern, because returned class will be binding, not property. 我将违反JavaFX属性模式,因为返回的类将是绑定的,而不是属性。

Hence, I need to wrap result into property, but how? 因此,我需要将结果包装到属性中,但是如何呢?

If I write 如果我写

class MyTable {
   private ReadOnlyBooleanPropertyBase previousExist = new ReadOnlyBooleanPropertyBase() {
      @Override
      public boolean get() {
         return getIndex() >= 0;
      }
      ...
   }
}

I will be unable to rely on change reporting and will be required to listen index changes explicitly and fire them forward. 我将无法依靠变更报告,并且将被要求明确地监听索引变更并将其向前发送。

So, how to implement? 那么,如何实施呢?

ReadOnlyBooleanWrapper is to use: ReadOnlyBooleanWrapper将使用:

private ReadOnlyBooleanWrapper previousExist;
{
   ReadOnlyBooleanWrapper ans = new ReadOnlyBooleanWrapper();
   ans.bind( currentRowProperty().greaterThan(0) );
   previousExist = ans;
}

public ReadOnlyBooleanProperty previousExist() {
   return previousExist.getReadOnlyProperty();
}

public boolean isPreviousExist() {
   return previousExist().get();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM