Saturday, February 2, 2013

JavaFX in a Swing application

I've tried multiple libraries to play audio before settling with JavaFX, and they all sucked. These were not intuitive, and not easy to operate.

JavaFX on the other hand, is simple quick and does the work elegantly. There are a few issues I have with their design such as:

  • No exception throwing!!!
  • When playing media there are three threads been created and destroyed rapidly, for the entire duration of the playing. (WTH???)
In any case, I've needed a way to play my audio files but I didn't like this sort of API, so I've wrapped it with my own interfaces and all, but then I've learned that JavaFX needed to be initialized or it would throw:

java.lang.IllegalStateException: Toolkit not initialized

So... here is what you need to do:

 private void initJavaFX() {
  final CountDownLatch latch = new CountDownLatch(1);

  new Thread(new Runnable() {

   @Override
   public void run() {
    @SuppressWarnings("unused")
    JFXPanel p = new JFXPanel();
    latch.countDown();
   }
  }, "JavaFX-initializer").start();
  try {
   latch.await();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

This would initialize JavaFX framework, and allow you to play media...

1 comment: