原文链接:https://stackoverflow.com/questions/12575201/how-to-save-a-image-on-jframe
考虑到截图保存窗口如果被其他置顶窗口挡住,或者窗口在屏幕外的话无效了,所以采用如下方法。
public void savePic(JFrame jf){ //得到窗口内容面板 Container content=jf.getContentPane(); //创建缓冲图片对象 BufferedImage img=new BufferedImage( jf.getWidth(),jf.getHeight(),BufferedImage.TYPE_INT_RGB); //得到图形对象 Graphics2D g2d = img.createGraphics(); //将窗口内容面板输出到图形对象中 content.printAll(g2d); //保存为图片 File f=new File("saveScreen.jpg"); try { ImageIO.write(img, "jpg", f); } catch (IOException e) { e.printStackTrace(); } //释放图形对象 g2d.dispose(); }