Java Reference
In-Depth Information
Once the media player is created, you create a java.lang.Runnable to be set
to the onReady attribute to be invoked when the media is in a ready state. Once the
ready event is realized, the run() method will call the media player object's play()
method to begin the audio. With the dragged-drop sequence completed, you appropri-
ately notify the drag-and-drop system by invoking the event's setDropCom-
pleted() method with a value of true . The following code snippet demonstrates
how to implement a Runnable to begin the media player as soon as the media player
is in a ready state using a method reference:
mediaPlayer.setOnReady(mediaPlayer::play);
Finally, you create buttons with JavaFX shapes to represent the stop, play, pause,
and close buttons. When creating shapes or custom nodes, you can add event handlers
to nodes in order to respond to mouse clicks. Although there are advanced ways to
build custom controls in JavaFX, this example uses custom-built button icons from
simple rectangles, arcs, circles, and lines. To see more advanced ways to create custom
controls, refer to the Javadoc on the Skinnable API or to Recipe 16-5. To attach
event handlers for a mouse press, simply call the setOnMousePress() method by
passing in an EventHandler<MouseEvent> instance. The following code demon-
strates adding an EventHandler to respond to mouse press on the stopButton
node:
stopButton.setOnMousePressed((MouseEvent me) -> {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
});
Because all the buttons use the same code snippet, only the method calls that each
button will perform on the media player are listed. The last button, Close, isn't related
to the media player, but it provides a way to exit the MP3 player application. The fol-
lowing actions are responsible for stopping, pausing, playing, and exiting the MP3
player application:
Stop - mediaPlayer.stop();
Pause - mediaPlayer.pause();
Play - mediaPlayer.play();
Close - Platform.exit();
Search WWH ::




Custom Search