拍摄完整 JFrame 和仅 Jframe 的快照

take snapshot of full JFrame and Jframe only

大家好,我已经开发了一个代码来截取整个屏幕的屏幕截图,但我希望它只截取 Jframe 中的内容。顺便说一下,我稍后会用它来打印图像。主要问题之一是,鼠标也出现在快照中。我不想要鼠标或底部的两个按钮。我可以改变按钮的 visi,但是鼠标和 Jframe 内部只拍摄应该做什么?这是我的代码,它拍摄了整个屏幕的屏幕截图。

                try{
                Thread.sleep(1000);
                Toolkit tk = Toolkit.getDefaultToolkit(); //Toolkit class                         returns the default toolkit
                Dimension d = tk.getScreenSize();

//Dimension class object stores width & height of the toolkit screen
// toolkit.getScreenSize() determines the size of the screen

                Rectangle rec = new Rectangle(0, 0, d.width, d.height);  
//Creates a Rectangle with screen dimensions,         

                Robot ro = new Robot(); //to capture the screen image
                BufferedImage img = ro.createScreenCapture(rec);



                File f;
                f = new File("myimage.jpg"); // File class is used to write the above generated buffered image to a file
                ImageIO.write(img, "jpg", f);

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

恕我直言,最好为您的组件制作图像(JFrame 也是 Component):

BufferedImage img = new BufferedImage(yourComponent.getWidth(), yourComponent.getHeight(), BufferedImage.TYPE_INT_RGB);
yourComponent.paint(img.getGraphics());
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);