【问题标题】:How to implement derived read-only properties/values in JavaFX?如何在 JavaFX 中实现派生的只读属性/值?
【发布时间】:2016-05-06 09:04:41
【问题描述】:

假设我有一个对象,代表数据库表,它有属性,表示当前选定的行:

class MyTable {

   private IntegerProperty currentRow ...

   public IntegerProperty currentRowProperty() {
      return currentRow;
   }

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

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

现在我希望有额外的显式只读实体来表示,该行是否可以移动到上一个(绑定到“上一个”按钮)。

如果我用绑定实现它

class MyTable {

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

   public BooleanBinding previousExistBinding() {
      return previousExist;
   }

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

我将违反 JavaFX 属性模式,因为返回的类将是绑定的,而不是属性。

因此,我需要将结果包装到属性中,但是如何?

如果我写

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

我将无法依赖更改报告,并且将被要求明确地监听索引更改并向前触发。

那么,如何实现呢?

【问题讨论】:

    标签: java javafx properties


    【解决方案1】:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多