我正在尝试对JPanel的功能进行截图,但保存后会得到黑色图像。
这是代码:
private void takeScreenshot(String print){
JFileChooser c = new JFileChooser(getRealDesktop());
FileFilter jpg = new FileNameExtensionFilter(".jpg", ImageIO.getReaderFileSuffixes());
FileFilter jpeg = new FileNameExtensionFilter(".jpeg", ImageIO.getReaderFileSuffixes());
FileFilter png = new FileNameExtensionFilter(".png", ImageIO.getReaderFileSuffixes());
c.setFileFilter(png);
c.setFileFilter(jpeg);
c.setFileFilter(jpg);
c.showSaveDialog(this);
if(c.getSelectedFile() != null){
String ssLoc = c.getSelectedFile().getAbsolutePath()+c.getFileFilter().getDescription();
System.out.println(ssLoc);
BufferedImage bufImg = new BufferedImage(ssWindow.getSize().width, ssWindow.getSize().height,BufferedImage.TYPE_INT_RGB);
ssWindow.paint(bufImg.createGraphics());
File imageFile = new File(ssLoc);
try{
imageFile.createNewFile();
ImageIO.write(bufImg, "JPG", imageFile);
}catch(Exception ex){
System.err.println(ex);
}
}
}
按下动作按钮如下所示:
this.setVisible(false);
takeScreenshot("ssTake");
this.setVisible(true);
如何使这项工作?
最佳答案
谢谢,吉尔伯特·勒布朗。
我重新编写了一些代码以使用机器人来执行此操作,现在代码如下所示:
private void takeScreenshot(String print){
JFileChooser c = new JFileChooser(getRealDesktop());
FileFilter jpeg = new FileNameExtensionFilter("JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)", "jpg", "jpeg", "jpe", "jfif");
c.setFileFilter(jpeg);
c.showSaveDialog(this);
if(c.getSelectedFile() != null){
ssLoc = c.getSelectedFile().getAbsolutePath()+".jpg";
try {
Thread.sleep(150);
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(ssWindow.getX(),ssWindow.getY(),ssWindow.getWidth(),ssWindow.getHeight()));
ImageIO.write(screenShot, "JPG", new File(ssLoc));
System.out.println(print);
} catch (AWTException | IOException | InterruptedException ex) {
Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}