javafx in swing exception “Toolkit not initialized

2019-08-03 05:20发布

问题:

I've read the post: JavaFx 2.x - Swing : Not on FX application thread

with reference to " Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Toolkit not initialized "

I have found a discussion here JavaFX 2.1: Toolkit not initialized

but I am not able to use the solution

"Istantiate JFXPanel in Swing Event Dispatcher Thread:"

because it stay undefined time waiting.

I have your same problem using a JInternalFrame inside a JDesktopPane.

I've tried:

final CountDownLatch latch = new CountDownLatch(1);
SwingUtilities.invokeLater(new Runnable() {
  @Override
  public void run() {
    final JFXPanel javafxPanel = new JFXPanel();
    latch.countDown();       
    BorderPane pane = new BorderPane();
    javafxPanel.setScene( new Scene(pane) {
      Text text = new Text("Hello World");            
    });
    frame.getContentPane().add(javafxPanel, BorderLayout.CENTER);
  }
});        
this.add(frame);
try {
    latch.await();
} catch (InterruptedException ex) {
    System.out.println("err");
    Logger.getLogger(WorkspacePanel.class.getName()).log(Level.SEVERE, null,     ex);
}

Where frame is a JInternalFrame and this is a JDesktopPane.

Any help ? Thanks in advance.

回答1:

because it stay undefined time waiting.

This waiting can be caused by the latch. If the code you posted is triggered on the Event Dispatch Thread, the latch.await() call will block the EDT and making sure the Runnable which you posted on the EDT will never executed, hence the latch.countDown() statement is never reached. You can quickly check this with the method EventQueue.isDispatchThread.

I would strongly suggest to simply remove the CountDownLatch, as running that code on another Thread is not an option since you are working with Swing components, which should be accessed/modified/created/... on the Event Dispatch Thread.

Further, once you have removed the latch you will encounter the same exception as in the linked question. The

javafxPanel.setScene( new Scene(pane) {
  Text text = new Text("Hello World");            
});

must be executed on the JavaFX thread and not on the Event Dispatch Thread. See my answer on that question on how to solve that.