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

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

本文介绍了如何在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).

如果我使用Binding实现它

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

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

I will violate JavaFX property pattern, because returned class will be binding, not property.

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

Hence, I need to wrap result into property, but how?

如果我写了

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.

那么,如何实现?

推荐答案

将使用:

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

这篇关于如何在JavaFX中实现派生的只读属性/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:36