我正在尝试使用JavaFX构建媒体播放器。首先,我加载了一个视频,接下来我创建了一个暂停按钮,工作正常。当我用打开的按钮加载新视频时(" apri")视频正常工作,但暂停按钮无法正常工作-_-这是我的主要课程..我没有使用过场景制作者,但我只尝试使用代码
public class Main extends Application {
public String indirizzo = "file:///C:/Users/ASUS/Desktop/film/prova1.mp4";
@Override
public void start(Stage primaryStage) {
try {
/* Creo la scena e mi faccio passare il media da visualizzare */
/* Creo i pannelli */
BorderPane bp = new BorderPane();
StackPane sp = new StackPane();
HBox hb = new HBox(5);
VBox vb = new VBox();
/* Primo video */
MediaView mv = new MediaView();
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
mv.setMediaPlayer(mp);
mp.play();
/* Creo gli oggetti nella parte bassa*/
Slider misc = new Slider();
Slider sl = new Slider();
Label volume = new Label("Volume: ");
Button btn1 = new Button("Apri");
Button btn2 = new Button("<<");
Button btn3 = new Button("| |");
Button btn4 = new Button(">>");
hb.setAlignment(Pos.CENTER);
hb.setPadding(new Insets(5,10,5,10));
/* Dimensioni slider */
sl.setPrefWidth(70);
sl.setMinWidth(30);
sl.setValue(100);
/* Posiziono i pannelli */
bp.setCenter(mv);
hb.getChildren().addAll(btn1,btn2,btn3,btn4,volume,sl);
vb.getChildren().addAll(misc,hb);
bp.setBottom(vb);
/* Se schiaccio il pulsante apri */
btn1.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
/* Prima metto in pausa il video */
FileChooser fc = new FileChooser();
ExtensionFilter filtro = new ExtensionFilter("Seleziona media (*.mp4)","*.mp4");
fc.getExtensionFilters().add(filtro);
/* Apro la finestra di dialogo per caricare il file */
File file = fc.showOpenDialog(null);
indirizzo = file.toURI().toString();
if(file != null){
/* Carico il media nel mp */
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
mv.setMediaPlayer(mp);
/* Imposto dimensione Media View*/
mv.setFitHeight(500); /* Vanno bindate con la scene*/
mv.setFitWidth(500);
mp.play();
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);
}
}
});
btn3.setOnAction((ActionEvent e) -> {
Status currentStatus = mp.getStatus();
if(currentStatus == Status.PLAYING)
mp.pause();
else if(currentStatus == Status.PAUSED || currentStatus == Status.STOPPED){
mp.play();
}
});
Scene scena = new Scene(bp,500,500);
scena.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scena);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
答案 0 :(得分:1)
问题在于:
if(file != null){
/* Carico il media nel mp */
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
您正在使用mp
处理程序无法看到的新变量btn3.setOnAction()
。
要解决这个问题,请MediaPlayer mp
一个班级&#39;字段并且不要使用mp
名称引入新变量。