1

I have a private list and I don't want that it can be modified from outside in general. Just adding from outside is allowed and only if the object is valid. Therefore I used to write it like this:

private List<Object> list = new ArrayList<>();

public List<Object> getList()
{
    return Collections.unmodifiableList(list);
}

public void addObject(Object object)
{
    if (isObjectValid(object)) //any validation
        list.add(object);
}

Now for JavaFX purposes I turn the list to a property:

private ListProperty<Object> list =
               new SimpleListProperty<>(FXCollections.observableArrayList());

To profit from the benefits of an property like data binding and the ListChangeListener I have to provide the property to the outer world. But then access to all methods of a list is provided, too. (To use a ReadOnlyListProperty has no effect since the list instance itself will never change.) What can I do to achieve all goals:

  • private ListProperty
  • ListChangeListener can be added from outside
  • Usable for binding dependencies from outside (the create methods form class Bindings)
  • No modifying of the property or list instance itself
  • Modifying of list content from outside only through my own methods
Arceus
  • 520
  • 6
  • 16

1 Answers1

1

Not tested, but try:

private ListProperty<Object> list = new SimpleListProperty<>(FXCollections.observableArrayList());

private ReadOnlyListWrapper<Object> publicList = new ReadOnlyListWrapper<>();

and in the constructor:

publicList.bind(Bindings.createObjectBinding(
    () -> FXCollections.unmodifiableObservableList(list.getValue()),
    list));

then your accessor method is

public ReadOnlyListProperty<Object> getList() {
    return publicList.getReadOnlyProperty();
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Great, I've tested it and it seems to fulfill all goals! However, your bind method misses a bracket and the method from FXCollections is called unmodifiableObservableList(). – Arceus Jan 12 '16 at 05:17
  • If this solves your requirement, please remember to mark it as a solution. – hotzst Jan 12 '16 at 06:30
  • @Arceus Thanks for pointing out the typos (as you can guess I just typed it in directly): now fixed. – James_D Jan 12 '16 at 12:01