Java Reference
In-Depth Information
Listing 9-16.
The Logic Behind the Play/Pause Button
private Button createPlayPauseButton() {
URL url = getClass().getResource("resources/pause.png");
pauseImg = new Image(url.toString());
url = getClass().getResource("resources/play.png");
playImg = new Image(url.toString());
playPauseIcon = new ImageView(playImg);
final Button playPauseButton = new Button(null, playPauseIcon);
playPauseButton.setId("playPauseButton");
playPauseButton.setOnAction((ActionEvent arg0) -> {
final MediaPlayer mediaPlayer = songModel.getMediaPlayer();
if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
mediaPlayer.pause();
} else {
mediaPlayer.play();
}
});
return playPauseButton;
}
The first step in creating the
playPauseButton
is to load the two images that will serve as the button's
icons. The
playPauseIcon
, an
ImageView
, is then initialized with the
play Image
. This
ImageView
serves as the
playPauseButton
's graphic node. The two
Image
s and the
ImageView
are private members of the
PlayerControlsView
class because we need to access them later to set the button's icon according to the state of the media player.
The
playPauseButton
is also given an ID that is used by the application's style sheet to apply additional styles to
the button. These styles make the button's background completely transparent unless the mouse is currently hovering
over it. In that case, a translucent background is applied to give the user some visual feedback that the button is live.
These styles are shown in the following code fragment.
#playPauseButton {
-fx-background-color: transparent;
}
#playPauseButton:hover {
-fx-background-color: rgb(255, 255, 255, 0.1);
}
To switch the icon of the
playPauseButton
based on the state of the
MediaPlayer
, we need to listen to the
MediaPlayer
's
status
property. Unfortunately, the status property is not updated on the JavaFX application thread, so
we cannot bind the button's icon directly to the property. Doing so would violate JavaFX's threading rules and could
lead to “undefined behavior.”
■
the
status
and
currentTime
properties are updated by the
MediaPlayer
and, as of JavaFX version 2.0.2,
these updates do not occur on the JavaFX application thread. therefore, you cannot bind to these properties or use them
in binding expressions that affect live scene graph nodes. doing so will result in strange bugs or exceptions because this
violates the threading conventions of JavaFX.
Caution
Search WWH ::
Custom Search