How do I make JavaFX MediaView stretch media to fill parent container?

user3530525 picture user3530525 · Aug 2, 2014 · Viewed 8.2k times · Source

I'm trying to make my video's dimensions stretch automatically and fill the MediaView and maintain the original aspect ratio of the video. Basically, I want my MediaPlayer to fit the parent container on resize etc. like pretty much all video players do.

If anyone could shed some light on how to achieve this that would be much appreciated, thanks.

Answer

kbickar picture kbickar · Aug 7, 2015

Here's an example of stretching to the containing Scene and the scene is set by the Dimension "size":

final MediaPlayer videoPlayer = new MediaPlayer(
    new Media(new File(videoPath).toURI().toString()));
MediaView mv = new MediaView(videoPlayer);
DoubleProperty mvw = mv.fitWidthProperty();
DoubleProperty mvh = mv.fitHeightProperty();
mvw.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
mvh.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));
mv.setPreserveRatio(true);

setScene(new Scene(new Group(mv), size.getWidth(), size.getHeight()));