I'm trying to embed Swing content in a larger JavaFX application, however I can't get the embedded JPanel to have a transparent background. The JPanel only paints some of its area. I'd like the green to "show through", i.e. remove the light grey background in picture below.

public class TransparentSwingNode extends Application {
@Override
public void start(Stage stage) {
BorderPane pane = new BorderPane();
pane.setStyle("-fx-background-color: green");
final SwingNode swingNode = new SwingNode();
BorderPane.setMargin(swingNode, new Insets(20));
createAndSetSwingContent(swingNode);
pane.setCenter(swingNode);
// swingNode.setStyle("-fx-background-color: transparent"); // doesn't work
stage.setScene(new Scene(pane, 240, 240));
stage.show();
}
private void createAndSetSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JPanel panel = new DummyPanel();
panel.setOpaque(false);
// panel.setBackground(null); // doesn't work
// panel.setBackground(new Color(0, 0, 0, 0)); // Doesn't work
swingNode.setContent(panel);
}
});
}
private class DummyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(getHeight() / 4, getHeight() / 4, getWidth() / 2, getHeight() / 2);
}
}
public static void main(String[] args) {
launch(args);
}
}
I've tried
- various combinations of setOpaque(false), setBackground(null), etc.
- Setting the background of the SwingNode to transparent
- Lots of searching
Update
- We've found a workaround, see answer. However I'd still be interested in finding a better more stable way of doing this...
