Javafx: "Toolkit" Not Initialized When Trying to Play an Mp3 File Through Mediaplayer Class

JavaFX: Toolkit not initialized when trying to play an mp3 file through MediaPlayer class

JavaFX performs "hidden" initialization on start. Running MediaPlayer doesn't trigger initialization.

The easiest ways to trigger it are:

  • have Application.launch() executed
  • have Application based program being run from jar packaged by fx ant tasks (e.g. built from Netbeans JavaFX project)
  • have JFXPanel started
  • call Platform.startup(Runnable) (Java 9+)

Java audio is not loading. toURI not working?

The problem here is that MediaPlayer is meant to be use in a JavaFX application only so you need to convert your application as a JavaFX application if you want to be able to use it.

To convert your class into a JavaFX application you need:

  1. To make your class SoundTest extends javafx.application.Application
  2. And modify your main method as next

    public static void main(String[] args) {
    Application.launch(args);
    }

  3. You can then call the method sound in your implementation of start

JavaFX 2.1: Toolkit not initialized

Found a solution. If I just create a JFXPanel from Swing EDT before invoking JavaFX Platform.runLater it works.
I don't know how reliable this solution is, I might choose JFXPanel and JFrame if turns out to be unstable.

public class BootJavaFX {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JFXPanel(); // this will prepare JavaFX toolkit and environment
Platform.runLater(new Runnable() {
@Override
public void run() {
StageBuilder.create()
.scene(SceneBuilder.create()
.width(320)
.height(240)
.root(LabelBuilder.create()
.font(Font.font("Arial", 54))
.text("JavaFX")
.build())
.build())
.onCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent windowEvent) {
System.exit(0);
}
})
.build()
.show();
}
});
}
});
}
}


Related Topics



Leave a reply



Submit