Reputation: 95
I'm quite a newbie on JavaFX and I need to bind the visible property of a Label
in a way that, if the value it represents reaches 0, the Label
should be invisible. Also, it needs to be updated when the bounded integerProperty
value changes.
This is my code:
@FXML
private Label kingRewardLabel;
// many other stuff between
IntegerProperty kingBonus = mainApp.getLocalModel().getMap().kingBonus();
kingBonus.addListener((observable, oldValue, newValue) -> {
if (newValue.equals(0)) {
kingRewardLabel.setVisible(false);
} else {
kingRewardLabel.setText(String.valueOf(newValue.intValue()));
}
});
// testing the listener
kingBonus.setValue(25);
I have already tried to debug a little but everything seems fine, no error, no exception thrown, just the listener does not work, or at least not as I expect, because the Label
still show the default text "Label", instead of "25"
Upvotes: 2
Views: 3960
Reputation: 21799
You can use simply bindings to achieve this:
kingRewardLabel.textProperty().bind(kingBonus.asString());
kingRewardLabel.visibleProperty().bind(kingBonus.greaterThan(0));
The Label
kingRewardLabel
will display the value of the IntegerProperty
kingBonus
and it is only visible if the displayed value is greater than zero.
But, if you want to stay with listeners:
kingBonus.addListener((obs, oldVal, newVal) -> {
kingRewardLabel.setVisible(newVal.intValue() > 0);
kingRewardLabel.setText(newVal.toString());
});
This is almost the same as your listener in the question, but in that case, if the Label
became invisible, it will never become visible again as kingRewardLabel.setVisible(true)
is never called.
Finally, to answer your question about why the listener is "not working" - there can be two possible reasons:
1) The Label
, which one is displayed is not the Label
stored in kingRewardLabel
2) At the time when you call kingBonus.setValue(25);
, the value stored in kingBonus
is already 25, no changed event will be fired, therefore the listener is not executed at all.
Upvotes: 8
Reputation: 7255
You can go like this:
kingBonus.addListener(l -> {
int value = kingBonus.getValue().intValue();
System.out.println("Entered listener for value:" + value);
if (value == 0)
kingRewardLabel.setVisible(false);
else
kingRewardLabel.setText(value+"");
});
});
Upvotes: 0