0

i want to make a screenshot of the panel that i have created and the code is given below. Can any body please tell me why i am not getting.thanks

    public static final void makeScreenshot(JFrame argFrame) 
    {
      Rectangle rec = argFrame.getBounds();
      BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
      argFrame.paint(bufferedImage.getGraphics());

    try 
   {
        // Create temp file.
        File temp = File.createTempFile("C:\\Documents and Settings\\SriHari\\My Documents\\NetBeansProjects\\test\\src\\testscreenshot", ".jpg");

        // Use the ImageIO API to write the bufferedImage to a temporary file
        ImageIO.write(bufferedImage, "jpg", temp);

        //temp.deleteOnExit();
    } 


   catch (IOException ioe) {} 
  } // 
        public static void main(String args[])
        {
           TimeTableGraphicsRunner ts= new TimeTableGraphicsRunner();
           for(long i=1;i<1000000000;i++);
           ts.makeScreenshot(jf);
            System.out.println("hi");
        }
mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

1

The following works for me:

public static void main (String [] args)
{
    final JFrame frame = new JFrame ();

    JButton button = new JButton (new AbstractAction ("Make Screenshot!")
    {
        @Override
        public void actionPerformed (ActionEvent e)
        {
            Dimension size = frame.getSize ();
            BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
            Graphics g = img.getGraphics ();
            frame.paint (g);
            g.dispose ();
            try
            {
                ImageIO.write (img, "png", new File ("screenshot.png"));
            }
            catch (IOException ex)
            {
                ex.printStackTrace ();
            }
        }
    });

    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.getContentPane ().setLayout (new BorderLayout ());
    frame.getContentPane ().add (button, BorderLayout.CENTER);
    frame.pack ();
    frame.setVisible (true);
}

It does not render window title and border because this is handled by OS, not Swing.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
  • thanks a lot but can you please tell me why mine is not working. Looking for an quick and positive reply from your side. –  Feb 09 '13 at 08:56
  • Your example is incomplete, so it is hard to tell why is does not work. Could you please post complete example that others can run? – Mikhail Vladimirov Feb 09 '13 at 08:58
  • thanks again, I have a long code and for this i am not able to send you the code here.If you do not mind can i ask your email id else please tell me how to send here. –  Feb 09 '13 at 09:17
  • yes its true it does not render window title and border But i am getting a black BOrder and window. can this black border removed if not can it made white ? –  Feb 09 '13 at 09:36
  • i am waiting for your answer –  Feb 09 '13 at 09:41
  • i tried this code but i get a black screen shot. What could be wrong? – Nitesh Verma Apr 26 '13 at 17:58
1

You could try using something like Robot#createScreenCapture

enter image description here

If you don't want to capture the whole screen, you can use Component#getLocationOnScreen to find the position of the component on the screen instead...

public class CaptureScreen {

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

    public CaptureScreen() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;

                frame.add(new JLabel("Smile :D"), gbc);

                JButton capture = new JButton("Click");
                capture.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Robot robot = new Robot();
                            Rectangle bounds = frame.getBounds();
                            bounds.x -= 1;
                            bounds.y -= 1;
                            bounds.width += 2;
                            bounds.height += 2;
                            BufferedImage snapShot = robot.createScreenCapture(bounds);
                            ImageIO.write(snapShot, "png", new File("Snapshot.png"));
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });

                frame.add(capture, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

}

Example using Component#getLocationOnScreen

enter image description here

public class CaptureScreen {

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

    public CaptureScreen() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;

                frame.add(new JLabel("Smile :D"), gbc);

                JButton capture = new JButton("Click");
                capture.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Robot robot = new Robot();
                            Container panel = frame.getContentPane();
                            Point pos = panel.getLocationOnScreen();
                            Rectangle bounds = panel.getBounds();
                            bounds.x = pos.x;
                            bounds.y = pos.y;
                            bounds.x -= 1;
                            bounds.y -= 1;
                            bounds.width += 2;
                            bounds.height += 2;
                            BufferedImage snapShot = robot.createScreenCapture(bounds);
                            ImageIO.write(snapShot, "png", new File("Snapshot.png"));
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });

                frame.add(capture, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

}

Another Example show Component#getLocationOnScreen

enter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description here

The main reason 3 of the image are the same, is because the example dumps the root pane, layerd pane and content pane...

public class CaptureScreen {

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

    public void save(Component comp, File file) {
        if (comp.isVisible()) {
            try {
                System.out.println(comp);
                Robot robot = new Robot();
                Rectangle bounds = new Rectangle(comp.getLocationOnScreen(), comp.getSize());
                bounds.x -= 1;
                bounds.y -= 1;
                bounds.width += 2;
                bounds.height += 2;
                BufferedImage snapShot = robot.createScreenCapture(bounds);
                ImageIO.write(snapShot, "png", file);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private int layer;

    public void capture(Container container) {
        layer = 1;
        captureLayers(container);
    }

    public void captureLayers(Container container) {
        save(container, new File("SnapShot-" + layer + "-0.png"));
        int thisLayer = layer;
        int count = 1;
        for (Component comp : container.getComponents()) {
            if (comp instanceof Container) {
                layer++;
                captureLayers((Container) comp);
            } else {
                save(comp, new File("SnapShot-" + thisLayer + "-" + count + ".png"));
                count++;
            }
        }
    }

    public CaptureScreen() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;

                frame.add(new JLabel("Smile :D"), gbc);

                JButton capture = new JButton("Click");
                capture.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        capture(frame);
                    }

                });

                frame.add(capture, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thanks for replying but i did not want the output like the way you programmed.I have a frame with 2 panels embedded,one within another and i want to make the screen shot of the panels(not frame) i have done it but i am getting a black border with black window title. Sorry to say its a long code and can not be pasted .If interested in code then let know how to send it(because in comments i have tried and it shows too long) –  Feb 09 '13 at 10:09
  • So. Grab the location of the panel (using getLocationOnScreen()) and generate a Rectangle to match... – MadProgrammer Feb 09 '13 at 10:16
  • if i drag then the size of the frame will increase and i do not want the frame screenshot,i want only the panel –  Feb 09 '13 at 10:26
  • Generate a rectangle based on the location of the panel on the screen and it's size...`Rectangle bounds = new Rectangle(panel.getLocationOnScreen(), panel.getSize());` and use these bounds to grab a capture of the screen. – MadProgrammer Feb 09 '13 at 10:28
  • have to read question by [@Hovercraft Full Of Eels](http://stackoverflow.com/questions/10468432/do-robot-methods-need-to-be-run-on-the-event-queue) – mKorbel Feb 09 '13 at 11:06
  • The two examples I've provide do two different things. The first captures the entire frame, the second captures the content pane. The outputs are different, as a tested to by the screen shots I've uploaded – MadProgrammer Feb 09 '13 at 11:08
  • @MadProgrammer sorry to say but i am getting same output in both the codes.I do not have enough reputation otherwise i would have attached here –  Feb 09 '13 at 11:23
  • 1
    Added another example. Can't say what you're doing wrong as it works nicely for me :P – MadProgrammer Feb 09 '13 at 11:25