Reputation: 27373
I'm working on a PDF viewer using JavaFX8 and have "page up" and "page down" button. I want the "page up" button to be disabled if the currently displayed page is the first page.
First, I haved added a isFirstPage BooleanProperty
instance variable to my controller (which I set to true or false depending on the current page number), this works fine, but it seems overkill to add an instance variable for every state of the application (isFirstPage, isLastPage, isDocumentLoaded etc).
What I want to achieve is to bind the disableProperty to a Predicate (whichs is evaluated every time the selectedPageNo changes), but apparently I'm doing somethign wrong as the code is not working (the buttons is never disabled):
nextPageButton.disableProperty().bind(Bindings.createBooleanBinding(() ->
selectedPageNo.intValue() >= currentDocument.getNumberOfPages()));
Here selectedPageNo
is a IntegerProperty
and currentDocument
a org.apache.pdfbox.pdmodel.PDDocument
Upvotes: 1
Views: 45
Reputation: 209684
Three different ways:
IntegerProperty
API
You can just do
nextPageButton.disableProperty().bind(
selectedPageNo.greaterThanOrEqualTo(currentDocument.getNumberOfPages()));
If the number of pages might change and is also represented by an IntegerProperty
, then
nextPageButton.disableProperty().bind(
selectedPageNo.greaterThanOrEqualTo(currentDocument.numberOfPagesProperty()));
will observe both properties and update as required.
Bindings API
For more general calculations that aren't supported by the methods IntegerProperty
inherits from NumberExpressionBase
, you can use the Bindings
API almost as you used it. The thing you omitted was to provide the properties that the binding needs to observe:
nextPageButton.disableProperty().bind(Bindings.createBooleanBinding(() ->
selectedPageNo.intValue() >= currentDocument.getNumberOfPages(),
selectedPageNo));
Subclass BooleanBinding
An alternative is to subclass BooleanBinding
directly:
nextPageButton.disableProperty().bind(new BooleanBinding() {
{
bind(selectedPageNo);
}
@Override
protected boolean computeValue() {
return selectedPageNo.intValue() >= currentDocument.getNumberOfPages();
}
});
Upvotes: 1