Java Reference
In-Depth Information
12 import javafx.scene.media.MediaPlayer;
13 import javafx.scene.media.MediaView;
14 import javafx.util.Duration;
15
16 public class MediaDemo extends Application {
17
private static final String MEDIA_URL =
18
"http://cs.armstrong.edu/liang/common/sample.mp4" ;
19
20 @Override // Override the start method in the Application class
21
public void start(Stage primaryStage) {
22
Media media = new Media(MEDIA_URL);
create a media
create a media player
create a media view
23
MediaPlayer mediaPlayer = new MediaPlayer(media);
24
MediaView mediaView = new MediaView(mediaPlayer);
25
26 Button playButton = new Button( ">" );
27 playButton.setOnAction(e -> {
28 if (playButton.getText().equals( ">" )) {
29 mediaPlayer.play();
30 playButton.setText( "||" );
31 } else {
32 mediaPlayer.pause();
33 playButton.setText( ">" );
34 }
35 });
36
37 Button rewindButton = new Button( "<<" );
38 rewindButton.setOnAction(e -> mediaPlayer.seek(Duration.ZERO));
39
40 Slider slVolume = new Slider();
41 slVolume.setPrefWidth( 150 );
42 slVolume.setMaxWidth(Region.USE_PREF_SIZE);
43 slVolume.setMinWidth( 30 );
44 slVolume.setValue( 50 );
45 mediaPlayer.volumeProperty().bind(
46 slVolume.valueProperty().divide( 100 ));
47
48 HBox hBox = new HBox( 10 );
49 hBox.setAlignment(Pos.CENTER);
50 hBox.getChildren().addAll(playButton, rewindButton,
51
create a play/pause button
add handler for button action
play media
pause media
create a rewind button
create a handler for rewinding
create a slider for volume
set current volume
bind volume with slider
add buttons, slider to hBox
new Label( "Volume" ), slVolume);
52
53 BorderPane pane = new BorderPane();
54 pane.setCenter(mediaView);
55 pane.setBottom(hBox);
56
57 // Create a scene and place it in the stage
58 Scene scene = new Scene(pane, 650 , 500 );
59 primaryStage.setTitle( "MediaDemo" ); // Set the stage title
60 primaryStage.setScene(scene); // Place the scene in the stage
61 primaryStage.show(); // Display the stage
62 }
63 }
place media view in a pane
The source of the media is a URL string defined in lines 17 and 18. The program creates a
Media object from this URL (line 22), a MediaPlayer from the Media object (line 23), and
a MediaView from the MediaPlayer object (line 24). The relationship among these three
objects is shown in FigureĀ 16.34.
 
 
Search WWH ::




Custom Search