0

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();
    }
}
John
  • 11
  • 1
  • 5
  • 3
    Don't, ever call `paint` directly. In you case, I would consider using `printAll` instead, but you might find that the component needs to be sized and laid out properly, which might be part of your problem, as the time between `setVisible` been called and the the component been realised on the screen and painted is variable – MadProgrammer Jan 11 '21 at 23:18
  • 3
    For [example](https://stackoverflow.com/questions/17690275/exporting-a-jpanel-to-an-image/17690351#17690351) – MadProgrammer Jan 11 '21 at 23:29
  • 2
    `// log exception` Umm.. OK. Is that *literally* how the code is written? Note that it takes a single line of code to do `e.printStackTrace();`. Put that **instead** of this confusing code comment that contains no useful information. **General tip:** For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Jan 12 '21 at 01:42
  • I just thought about saving you the time to read all the log writes I have there. Fixed to your suggestion but its irrelevant to the question. – John Jan 12 '21 at 06:22
  • While it won't really fix anything by itself, I suggest you refactor this code so that the graph painting is separate from the Swing classes like `JPanel`, `JFrame` etc. Instead you should have a `Graph` class with a `draw(Graphics2D g, Dimension size)` method, that can draw the graph into either a `JComponent` or a `BufferedImage`. – Harald K Jan 12 '21 at 16:23

0 Answers0