Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwingNode with transparent content

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.

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'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...
like image 719
Adam Avatar asked Feb 04 '15 20:02

Adam


1 Answers

My colleague finally tracked something down. The system property swing.jlf.contentPaneTransparent, i.e. -Dswing.jlf.contentPaneTransparent=true

Result

Transparent background using system property

I cannot find any official documentation on this apart from

  • a mention in RT-37810 - Swing Nodes have serious rendering artifacts when first displayed on the primary Stage

Also, we have an experimental undocumented option ("swing.jlf.contentPaneTransparent") to switch on SwingNode's transparency. That's to say that we probably shouldn't refuse transparency support, unless this requires serious efforts.

  • JavaOne "Swing 2 JavaFX" Powerpoint
like image 74
Adam Avatar answered Oct 11 '22 12:10

Adam