I'm trying to save a graph image using BufferedImage, Graphics2D and JAIHelper, but for some reason one of every 4-5 pics is saved with data lacking (the image is cut off). First I got a NullPointerexception, then I changed it a little and now it is a bit better, but still every 4-5 images I get a cut off image.
Here is my code:
@Override
public void saveGraph(State state, String fileName, IndexTable xVals, IndexTable yVals) {
    try {
        graphPanel.updateGraph(xVals, yVals);
        JPanel panel = graphPanel.getGraph();
        JFrame frame = new JFrame();
        try {
            frame.add(panel);
            frame.setSize(500, 350);
            frame.setVisible(true);
            BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            try {
                panel.paint(graphics);
                JAIHelper.saveImage(PlanarImage.wrapRenderedImage(image), fileName);
            } finally {
                if (graphics != null) {
                    graphics.dispose();
                }
            }
        } finally {
            frame.dispose();
        }       
    } catch (Exception e) {
        e.printStackTrace();
    }
}