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:
- To make your class
SoundTest
extendsjavafx.application.Application
And modify your
main
method as nextpublic static void main(String[] args) {
Application.launch(args);
}- You can then call the method
sound
in your implementation ofstart
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
Java Two Varargs in One Method
How to Encode Url to Avoid Special Characters in Java
How to Get Subnet Mask of Local System Using Java
Jframe.Dispose() VS System.Exit()
Alternative to Ui:Fragment in Jsf
Keystore Type: Which One to Use
@Preupdate and @Prepersist in Hibernate/JPA (Using Session)
Can't Rid of 'T' in Localdatetime
Jackson: How to Add Custom Property to the JSON Without Modifying the Pojo
Maximum Size of Hashset, Vector, Linkedlist
How to Create an Instance of Inner Class Using Java Reflection
How to Find Out If the Value Contained in a String Is Double or Not