我正在尝试将 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);
}
}
我试过了
- setOpaque(false)、setBackground(null)等的各种组合
- 将 SwingNode 的背景设置为透明
- 大量搜索
更新
- 我们找到了解决方法,请参阅答案。然而,我仍然有兴趣找到一种更好更稳定的方法来做这件事......
最佳答案
我的同事终于找到了一些东西。系统属性 swing.jlf.contentPaneTransparent
,即 -Dswing.jlf.contentPaneTransparent=true
结果
除了
之外,我找不到任何关于此的官方文档- 在 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.
关于java - 具有透明内容的 SwingNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330906/