SwingNode with transparent content

I am trying to embed Swing content in a larger JavaFX application, however I cannot force the embedded JPanel to have a transparent background. JPanel only draws part of its field. I would like the green to "show", i.e. Removed the light gray background in the image below.

Swing node with background

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 tried

  • various combinations of setOpaque (false), setBackground (null), etc.
  • Set SwingNode background for transparent
  • A lot of search

Update

  • We found a workaround, see answer. However, I would still be interested in finding a more stable way to do this ...
+4
source share
1 answer

- -. swing.jlf.contentPaneTransparent, .. -Dswing.jlf.contentPaneTransparent=true

Transparent background using system property

,

, ( "swing.jlf.contentPaneTransparent" ) SwingNode . , , , , .

+4

All Articles