In order to use media in a JavaFX application, you must have the following import statements:
import java.io.File;
import javafx.scene.image.*;
import javafx.scene.media.*;
Using both images and audio in a JavaFX application is a little roundabout. First, you must load the media into a File
. Then, you must instantiate an instance of the respective class, either Image
or Media
. Finally, to display the image or play the audio, you must create an ImageView
or a MediaPlayer
instance.
Let's see this in action:
package edu.govschool;
import java.io.File;
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.media.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class JavaFXMediaExample extends Application
{
// Our instance variables, or in this case
// our GUI elements.
private static File imageFile;
private static File audioFile;
private static Image image;
private static Media audio;
private static ImageView imageView;
private static MediaPlayer audioPlayer;
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage)
{
// You need to specify the filepath to your file.
// Windows users need to use double-backslashes,
// like so:
// C:\\Users\\bryce\\Pictures\\somePic.jpg
// If, however, your picture is hosted online, you
// can skip the imageFile and simply do:
// image = new Image("http://i.imgur.com/x0ml8.png");
// replacing the URL with the URL to your image.
imageFile = new File("/Users/bryce/Pictures/somePic.jpg");
image = new Image(imageFile.toURI().toString());
// Let's use a better image for this example...
Image testImage = new Image("http://www.teesforall.com/images/Archer_Danger_Zone_Gray.jpg");
imageView = new ImageView(testImage);
// Same thing goes for audio, except you can't load
// from URLs
audioFile = new File("/Users/bryce/NetBeansProjects/Graphics_PM/src/edu/govschool/dangerzone.mp3");
audio = new Media(audioFile.toURI().toString());
audioPlayer = new MediaPlayer(audio);
audioPlayer.setAutoPlay(true);
BorderPane pane = new BorderPane();
pane.setCenter(imageView);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Media Example");
primaryStage.show();
}
}