Drawing a JPanel to a BufferedImage, unexpected results

I'm building a node-based editor. Effectively it's Swing components on a giant carpet, connected with lines to denote relationships and flow of data. To achieve this I have my VisibleFrame with my Donatello JPanel that does the custom rendering. Donatello gets the Swing component of items in the view area, and then draws it like this:
private void drawOneNode(Graphics2D g,JPanel panel) {
    frame.add(panel);
    frame.pack();

    if (panel.getWidth() > 0 && panel.getHeight() > 0) {
        // create a BufferedImage the same size as the panel.
        BufferedImage bi = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
        // JPanel requires a Graphics2D object to draw to.  Create one from the BufferedImage.
        Graphics2D g2d = bi.createGraphics();
        // draw it.
        panel.paint(g2d);
        // done with the Graphics2D object.
        g2d.dispose();

        // TODO draw the node at the correct position
        int x = 0;//(int)camera.x;
        int y = 0;//(int)camera.y;

        // draw bitmap scaled to the screen
        g.drawImage(bi,
                x, y, x + panel.getWidth(), y + panel.getHeight(),
                0, 0, panel.getWidth(), panel.getHeight(),
                null);
    }
    frame.remove(panel);
}

Somehow Donatello is showing panel twice - once at my desired position and once in the top left corner. But I'm never connecting panel to Donatello, or frame to Donatello, so I'm not sure how this is possible. If I comment out
panel.paint(g2d)
both disappear. Anyone have a hint for me?
image.png
Was this page helpful?