我试图用Java编写一个简单的音乐剧。我尝试使用切换按钮进行音乐播放或暂停,具体取决于播放器当前是否正在播放。这是我的代码现在的样子:
public class Client extends Application {
private boolean isPlaying = false;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("clientUI.fxml"));
ToggleButton toggleButton = (ToggleButton) root.lookup("toggleButton");
File song = new File("Shed.mp3");
Media media = new Media(song.toURI().toURL().toExternalForm());
MediaPlayer mp = new MediaPlayer(media);
toggleButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
if (isPlaying()) {
mp.pause();
} else {
mp.play();
}
}
});
Scene s = new Scene(root);
primaryStage.setScene(s);
primaryStage.setResizable(false);
primaryStage.setTitle("Noisey");
primaryStage.show();
}
public boolean isPlaying() {
return isPlaying;
}
} 但是,在运行时,会收到此错误: `
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at application.Client.start(Client.java:32)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
... 1 more
Exception running application application.Client
有些东西告诉我这一行Caused by: java.lang.NullPointerException
at application.Client.start(Client.java:32)
是问题所在。