It can be done thanks to a JFXPanel
which allows to embed a JavaFX
component into a Swing
component and from a Swing
component you can easily create an Applet
.
Here is an example that draws a Java FX
Rectangle
into an Applet
:
public class Main extends Applet {
private void initAndShowGUI() {
// This method is invoked on Swing thread
final JFXPanel fxPanel = new JFXPanel();
fxPanel.setPreferredSize(new Dimension(100, 100));
add(fxPanel);
setVisible(true);
Platform.runLater(
new Runnable() {
@Override
public void run() {
initFX(fxPanel);
}
}
);
}
private static void initFX(JFXPanel fxPanel) {
// This method is invoked on JavaFX thread
final Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() {
final Rectangle rectangle = new Rectangle(100.0, 100.0);
rectangle.setFill(Color.BLACK);
return new Scene(new VBox(rectangle));
}
@Override
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
initAndShowGUI();
}
}
);
}
}
However Applets are outdated and will be removed soon so if you can avoid using them, just don't use them. Alternatively you can use the Deployment Toolkit library
to embed your JavaFX application
in a web page or launch it from a browser, more details about this approach here.