为什么这段代码不起作用,有人可以给我一个解决方案吗?
播放第一部电影效果很好,但在点击Button
后我丢失了MediaView
并且未播放下一个视频。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class VideoTest extends Application{
private MediaPlayer player;
private MediaView view;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
HBox box = new HBox();
player = new MediaPlayer(new Media("file:///C:/path/to/file"));
view = new MediaView();
view.setMediaPlayer(player);
player.play();
Button button = new Button("Next");
button.setOnAction(e->{
player.stop();
player = new MediaPlayer(new Media("file:///C:/path/to/file"));
view = new MediaView(player);
player.play();
});
box.getChildren().addAll(view,button);
Scene scene = new Scene(box,700,500);
primaryStage.setScene(scene);
primaryStage.show();
}
}
答案 0 :(得分:0)
您永远不会向场景添加新的媒体视图,因此您永远不会看到它。
只需将新播放器设置为现有的媒体视图(已经附加到场景中),而不是创建新的媒体视图。
button.setOnAction(e->{
player.stop();
player = new MediaPlayer(new Media("http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv"));
view.setMediaPlayer(player);
player.play();
});