具有透明内容的 SwingNode

Ada*_*dam 5 java swing javafx javafx-8

我正在尝试将 Swing 内容嵌入到更大的 JavaFX 应用程序中,但是我无法让嵌入的 JPanel 具有透明背景。JPanel 仅绘制其部分区域。我希望绿色“显示出来”,即删除下图中的浅灰色背景。

带背景的摆动节点

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过了

  • setOpaque(false), setBackground(null) 等的各种组合。
  • 将 SwingNode 的背景设置为透明
  • 大量搜索

更新

  • 我们找到了解决方法,请参阅答案。但是我仍然有兴趣找到一种更好更稳定的方法来做到这一点......

Ada*_*dam 5

我的同事终于找到了一些东西。系统属性swing.jlf.contentPaneTransparent,即-Dswing.jlf.contentPaneTransparent=true

结果

使用系统属性的透明背景

除了这个,我找不到任何官方文件

此外,我们有一个实验性的未记录选项(“swing.jlf.contentPaneTransparent”)来打开 SwingNode 的透明度。也就是说,我们可能不应该拒绝透明度支持,除非这需要认真的努力。