使用JavaFx属性设置只读 [英] Setting read only with a JavaFx property

查看:249
本文介绍了使用JavaFx属性设置只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个类中使用JavaFx ObjectProperty。我正在使用它来绑定绑定功能。问题是我希望人们能够绑定它,但不能改变它的价值。我不能想到一种种姓证明方式(人们不会有任何方式从外面改变它),但必须有一些方法来做到这一点。

I'm using a JavaFx ObjectProperty in one of my classes. I'm using it for the bind features. The issues is that I want people to be able to bind to it, but not to change the value. I can't think of a caste proof way to do this (where people won't have ANY way to change it from outside), but there must be some way to do it.

推荐答案

解决方案

您正在寻找 ReadOnlyObjectWrapper

示例

以下是示例tic tac toe game ,我写道:

class Square {

  enum State { EMPTY, NOUGHT, CROSS }

  private ReadOnlyObjectWrapper<State> state = 
    new ReadOnlyObjectWrapper<>(State.EMPTY);

  public ReadOnlyObjectProperty<State> stateProperty() {
    return state.getReadOnlyProperty();
  }

  public State getState() {
    return state.get();
  }

  public void pressed() {
    if (!game.isGameOver() && state.get() == State.EMPTY) {
      state.set(game.getCurrentPlayer());
      ...
    }
  }
}

解释

这允许Square的状态由属性表示,以便Square的外部用户可以绑定到Square的州,然而国家本身被封装在广场上,所以只有广场可以改变它自己的状态。

This allows the state of the Square to be a represented by a property so that external users of the Square can bind to the Square's state, yet the state itself is encapsulated in the Square so only the Square can change it's own state.

此模式的用法示例是SquareSkin对象,其中包含表示Square的可见节点。皮肤可以侦听对相关方的状态属性的更改,并更新它用于正确显示方块的图像。

An example of a usage for this pattern is a SquareSkin object which contains the visible nodes to represent the Square. The skin can listen for changes to the associated square's state property and update the image it uses to display the square appropriately.

要真正确保ReadOnlyWrapper中包含的Object值不能从外部改变,最好是使这些对象值不可改变(例如,对象没有setter函数,只有getter函数)。

To really ensure that the Object values enclosed in the ReadOnlyWrapper cannot be changed externally, it is best to make those Object values immutable (e.g. the Objects have no setter functions, only getter functions).

更多示例

我链接的游戏代码包含许多不同绑定模式和用法的其他示例(我将其部分编写为绑定练习,以了解如果在应用程序中使用大量绑定会发生什么)。

The game code I linked contains many other examples of different binding patterns and usages (I wrote it partially as a binding exercise to see what would happen if you use a lot of bindings in an app).

这篇关于使用JavaFx属性设置只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆