We’ve collected these simple code snippets to allow you learn JavaFX.

Example 1: Media

Study the following code:

Step 1: Create Project

  1. Open your favorite Java IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Our code will comprise the following java files:

  • MediaExample.java
  1. In your editor or IDE, create a file known as MediaExample.java.
  2. Then add the following code:

(a). MediaExample.java

We will start by adding some imports to this class:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

We will start by adding some imports to this class:

import java.io.File;
import java.net.MalformedURLException;

Through inheritance we will be able to derive properties from a parent class. However we have to extend that parent class. So we do that using the extends keyword.

public class MediaExample extends Application {

Our class will have the following methods:

  • void main(String[] args)
  • void start(Stage primaryStage) throws MalformedURLException

All Java applications have an entry point known as the main method. We will define it:

    public static void main(String[] args) {

Here is the full code:

package com.jenkov.javafx.media;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

import java.io.File;
import java.net.MalformedURLException;

/**
 * Shows a simple JavaFX Media, MediaPlayer and MediaView example, playing an MP4 video. Please note that the
 * video is downloaded from Pixabay.com. Please do not redistribute the video for any purpose. Download it from Pixabay
 * if you want to use it:
 *
 * https://pixabay.com/videos/golden-particles-overlay-decoration-48569/
 */

public class MediaExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws MalformedURLException {
        File mediaFile = new File("assets/media/Golden-48569.mp4");
        Media media = new Media(mediaFile.toURI().toURL().toString());

        MediaPlayer mediaPlayer = new MediaPlayer(media);

        MediaView mediaView = new MediaView(mediaPlayer);

        Scene scene = new Scene(new Pane(mediaView), 1024, 800);
        primaryStage.setScene(scene);
        primaryStage.show();

        mediaPlayer.play();

    }
}

Download

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License