java - 具有透明内容的 SwingNode

标签 java swing javafx javafx-8

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

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);
    }
}

我试过了

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

更新

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

最佳答案

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

结果

Transparent background using system property

除了

之外,我找不到任何关于此的官方文档

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.

关于java - 具有透明内容的 SwingNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330906/

相关文章:

java - 在 Java Swing 应用程序中导入 Excel (.xls)

java - 实现自定义组合框模型未能覆盖某些方法

javafx.scene.control.Dialog<R> 不会在按下 "x"时关闭

java - Failed to notify project evaluation listener 错误在 Android Studio

java - Appengine 多个模块本地开发 - Java

java - 如何使进度不确定的任务循环进行?

Javafx 组合框重置问题

javafx-2 - 如何将文本放入圆形对象中以从圆形的中心显示它?

java - 二叉搜索树 : Display contents of the tree in a tree like fashion (recursive)

java - 如何在 Java 中生成双倍长度的 3-DES key