Search code examples
javaswingpanelscreenshot

Java, start a screen capture lower than the panel


So I am trying to get a screen shot of my panel and the code below does perfect. I want to lower the starting point of the screenshot by like 200 pixels. If I do size.height-200 it raises the bottom . I will need to do that in the future but how do I lower the top too? Or will I need to do a different method?

System.out.println("Trying to screenshot");
                    Dimension size = getSize ();
                    BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
                    Graphics g = img.getGraphics ();
                    paint (g);
                    g.dispose ();
                    try
                    {
                        ImageIO.write (img, "png", new File ("screenshot1.png"));
                    }
                    catch (IOException ex)
                    {
                        ex.printStackTrace ();
                    }                   

Solution

  • Do you want to draw a component with an offset? If yes, then AffineTransformation is your friend. Try calling

        Graphics2D g = img.createGraphics();
        g.transform(AffineTransform.getTranslateInstance(0, -200));
        paint(g);
        g.dispose();