导致布局问题的节点快照

Node snapshot causing layout issue

我使用 JavaFX 9.0.4 在 JavaFX 应用程序中嵌入了一些第 3 方 Swing 内容。第 3 方内容已经有自己的首选大小,所以我用 StackPane 包装它。

但是,当调用 node.snapshot() 时,这会导致 SwingNode 跳回到其首选大小,手动调整 window 的大小会导致它再次填充 window。

我还发现,只有当场景首先显示时没有内容,然后才添加该内容时,才会发生这种情况。

这是一个错误吗?我该如何解决?

以下示例重现了该问题

public class NodeSnapshotFunny extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        SwingNode swingNode = new SwingNode();
        Button button = new Button("Test");
        button.setOnAction(event -> {
            WritableImage image = button.snapshot(null, null);
        });
        StackPane stackPane = new StackPane(swingNode);
        Scene scene = new Scene(stackPane);
        stage.setScene(scene);
        stage.show();
        stackPane.getChildren().add(button);

        SwingUtilities.invokeLater(() -> {
            JPanel jPanel = new JPanel();
            jPanel.setPreferredSize(new Dimension(300, 300));
            jPanel.setBackground(Color.red);
            swingNode.setContent(jPanel);
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}

我已将此问题作为错误提出并已被接受。参见 JDK-8198677。显然这是 8u40 中引入的回归。