2012-11-22 221 views
0

這是我在控制器:的JavaFX - 播放視頻與媒體播放器和mediaview

@FXML 
private MediaView mediaView; 

方式,來處理按鈕按下我得到了文件選擇:

File file = fileChooser.showOpenDialog(null); 

    if(file != null){ 
     initPlayer(file.toURI().toString()); 
    } 

,這是方法initPlayer:

private void initPlayer (String uri) { 
     if (uri == null) 
      return; 
     if (mediaPlayer != null) { 
      mediaPlayer.stop(); 
      mediaPlayer = null; 
     } 

     Media media = new Media(uri); 
     mediaPlayer = new MediaPlayer(media); 
     mediaPlayer.setAutoPlay(true); 
     mediaView = new MediaView(mediaPlayer); 
     mediaPlayer.setOnReady(new Runnable() { 
      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
      } 
     }); 
    } 

這是我在場景構建器中創建的視圖中代碼的一部分:

<Pane layoutX="80.0" layoutY="14.0" prefHeight="480.0" prefWidth="640.0"> 
      <MediaView fx:id="mediaView" fitHeight="480.0" fitWidth="640.0" /> 
     </Pane> 

當我選擇文件時,我聽到聲音但我沒有看到視頻。這段代碼有什麼問題?我錯過了什麼?

回答

4

A MediaView實例由FXMLLoader創建,並在加載FXML文件時放置在您的Pane中。

你不需要創建一個新的MediaView,當你這樣做的時候沒有被附加到場景中,這就是爲什麼你看不到任何東西。

相反的:

mediaView = new MediaView(mediaPlayer); 

寫:

mediaView.setMediaPlayer(mediaPlayer); 
+0

Ther e也必須是其他地方的問題。我認爲你是對的,但我試過了,並沒有幫助。那麼你有更多的想法嗎?謝謝 –

0

在你FXML你需要

<FlowPane alignment="CENTER" columnHalignment="CENTER" layoutX="9.0" layoutY="48.0" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="9.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="48.0"> 
<children> 
<MediaView fx:id="mediaView"> 
</MediaView> 
</children> 
</FlowPane> 

,並在你的控制器:

@FXML private MediaPlayer mediaPlayer; 
@FXML private Duration duration; 
@FXML private MediaView mediaView; 
.... 

@Override 
    public void initialize(URL url, ResourceBundle rb) { 
     try { 
      init(); 
     } catch (MalformedURLException ex) { 
      Logger.getLogger(MainOnlineController.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 


    public void init() throws MalformedURLException { 
     .... 
     mediaPlayer = new MediaPlayer(media); 
     mediaPlayer.setAutoPlay(true); 
     mediaView.setMediaPlayer(mediaPlayer); 
     mediaPlayer.setOnPlaying(new Runnable() { 
        public void run() { 
         if (stopRequested) { 
          mediaPlayer.pause(); 
          stopRequested = false; 
         } else { 
          playButton.setText("||"); 
         } 
        } 
       }); 
    ...other methods for mediaPlayer