Reputation: 175
I am trying to create a small JavaFX application.
What i am trying to do is this: My app has a TextField which the user cause to insert a url. Then you click a button to load the page. What i want to do is to have this button be disabled either when the TextField is empty or while the page loads. When the page finishes loading, the button is enabled again.
I used bindings to bind the TextField with the button, so when TextField is empty the button is disabled, using below code:
BooleanBinding booleanBind = new BooleanBinding() {
{
super.bind(url.textProperty());
}
@Override
protected boolean computeValue() {
return url.getText().isEmpty();
}
};
loadButton.disableProperty().bind(booleanBind);
Now i want to also disable the button when page loads. In order to load the page i use below code:
loadButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
//loadButton.setDisable(true);
webEngine.load(url.getText());
}
});
Commented you can see the way i was disabling the button while page was loading (i am using a ChangeListener to enable it again after WebEngine finishes loading). But now that i used the binding to also bind it with the TextField, i cant disable it manually like this because i get java.lang.RuntimeException: A bound value cannot be set.
error.
How can i use bindings to also disable the button while page loads?
Upvotes: 0
Views: 300
Reputation: 45746
A WebEngine
has a method for getting the Worker
used for performing the background loading: WebEngine.getLoadWorker()
. A Worker
has the running
property. Use this property and combine it with whether or not the TextField
's text
property is empty via an or binding.
BooleanBinding empty = textField.textProperty().isEmpty();
button.disableProperty().bind(empty.or(webEngine.getLoadWorker().runningProperty());
Also, as shown above, there is no need to create your own BooleanBinding
to hold the empty status of the TextField
. The text
property is a StringProperty
which extends from StringExpression
. The StringExpression
class has the isEmpty()
method which returns a BooleanBinding
for you.
Upvotes: 2