Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting read only with a JavaFx property

Tags:

java

javafx

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.

like image 307
sinθ Avatar asked Aug 06 '13 00:08

sinθ


1 Answers

Solution

You are looking for the ReadOnlyObjectWrapper.

Sample

Here is an example usage taken from a sample tic tac toe game which I wrote:

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

Explanation

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.

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.

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).

Further Examples

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).

like image 72
jewelsea Avatar answered Oct 17 '22 08:10

jewelsea