Skip to content
Advertisement

Bind java.util.Stack with JavaFX (ListView or TableView)

I’m recently using JavaFX and would like to implement the Observer pattern by binding my stack update, with a ListView or TableView from JavaFX. However, I don’t know what changes to make to my ComplexNumberStack class.

JavaScript

Advertisement

Answer

This example adds a wrapper class around your stack implementation which provides an ObservableList that can be:

  1. Placed in a ListView AND
  2. Respond to bindings (see the pop button disable property binding in the example app).

For it to work, the mutation operations (e.g. push/pop) must be called on the wrapper class rather than the underlying class.

There are more efficient ways of implementing this (e.g. don’t subclass stack, instead implement the Deque interface and use an ObservableList directly as storage, extending ObservableListBase).

However, this is what I came up with that still kept your underlying class and it might be fine or easily adaptable for your purposes.

popup


JavaScript

The underlying stack implementation is unchanged from the class in your question.

JavaScript

Provides observability for the stack.

JavaScript

Test application.

JavaScript

Potential alteratives or improvements

hmm .. this looks a bit brittle – external code could change the stack without notifying the list (especially, since is a singleton and potential collaborators spread across the world

Yes, it’s true, its buyer beware 🙂

The alternate proposed solution of implementing Deque with operations directly on a backing observableList is probably preferred, but I’m not going to write that at this time (it would be quite a bit more work to do well).

The solution in this answer uses the FXCollections list wrapper, which, incidentally, on its own is another simple solution to this problem:

JavaScript

Though, it has some disadvantages:

  1. Changes to the underlying stack will not be observed (also true of the solution in this answer).
  2. You need to change the list to observe changes and the list won’t have push/pop ops (unlike the solution in this answer, which does at least provide push/pop ops which will be observed).

If you are interested in how the JavaFX framework implementation wrapper works, you can see the code for ObservableListWrapper.

If you wished to, you could copy a version of ObservableListWrapper to your own package (you don’t want to depend on com.sun code directly), then subclass it and adapt it to add your additional push/pop ops (as suggested by kleopatra in comments).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement