Java Reference
In-Depth Information
The solution is to attach a listener to the property and use the Platform.runLater method to trigger updates on
the application thread. This code is shown in Listing 9-17.
Listing 9-17. Listening to Status Property Changes to Update the Scene Graph
private class StatusListener implements InvalidationListener {
@Override
public void invalidated(Observable observable) {
Platform.runLater(() -> {
updateStatus(songModel.getMediaPlayer().getStatus());
});
}
}
private void updateStatus(Status newStatus) {
if (newStatus == Status.UNKNOWN || newStatus == null) {
controlPanel.setDisable(true);
positionSlider.setDisable(true);
statusLabel.setText("Buffering");
} else {
controlPanel.setDisable(false);
positionSlider.setDisable(false);
statusLabel.setText(newStatus.toString());
if (newStatus == Status.PLAYING) {
playPauseIcon.setImage(pauseImg);
} else {
playPauseIcon.setImage(playImg);
}
}
}
The StatusListener inner class is an InvalidationListener that, once added to a MediaPlayer 's status
property, will be notified whenever the status property changes. Its job is to call out to the private updateStatus
method of its enclosing class on the JavaFX application thread. This makes it safe to update live scene graph nodes
from within the updateStatus method. One of those updates is to set the image of the playPauseIcon (an ImageView
node) as shown by the code that is highlighted within the updateStatus method.
We also update the text of the statusLabel that is used as the status display (refer back to Figure 9-5 ) as well as
enable or disable the playback controls and the position slider any time the status changes. If the MediaPlayer 's status
is UNKNOWN or null, the player is not ready to begin playback and we indicate this status by displaying the “Buffering”
string and disabling the playback controls. Any other MediaPlayer status will result in its name being displayed and
the playback controls being enabled.
The status display is shown as a text string with a border around it. This is accomplished simply by using a Label
control with some extra styling, which is shown in the following code.
.statusDisplay {
-fx-border-color: white;
-fx-border-radius: 2;
-fx-border-width: 1;
-fx-text-fill: white;
-fx-font-size: 10pt;
}
 
Search WWH ::




Custom Search