Javafx mediaViewer / mediaPlayer引发java.lang.reflect.InvocationTargetException和java.lang.NullPointerException

时间:2018-12-18 14:05:53

标签: java javafx javafx-8

所以我在这里有这段代码:

package sample;

import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.FileChooser;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    private MediaPlayer mediaPlayer;

    @FXML
    private MediaView mediaView;

    private String filePath;

    @FXML
    private void handleButtonAction (ActionEvent event){
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4");
        fileChooser.getExtensionFilters().add(filter);
        File file = fileChooser.showOpenDialog(null);
        filePath = file.toURI().toString();

        if(filePath != null) {
            Media media = new Media(filePath);
            mediaPlayer = new MediaPlayer(media);
            mediaView.setMediaPlayer(mediaPlayer);
            DoubleProperty width = mediaView.fitWidthProperty();
            DoubleProperty hight = mediaView.fitHeightProperty();

            width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width"));
            hight.bind(Bindings.selectDouble(mediaView.sceneProperty(), "hight"));

            mediaPlayer.play();
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }
}

您可以运行它。但是,如果您尝试使用openfile按钮打开文件,则视频将不会出现,而我仅获得例外列表。我不知道这只是我还是我做错了什么。

NullPointerExeption位于第38行,信任我正在使用的IntelliJ。

Caused by: java.lang.NullPointerException
 at sample.Controller.handleButtonAction(Controller.java:38))

那么mediaPlayer / mediaViewer有什么用吗? (mediaView.setMediaPlayer(mediaPlayer);)

1 个答案:

答案 0 :(得分:0)

所以我忘了做这行(或通过SceneBuilder添加)

<MediaView fx:id="mediaView" fitHeight="200.0" fitWidth="200.0" />