I'm creating a simple test program to take screenshots of the entire screen, after some research, I created the following code:
public class PrintScreenCatcher {
public String capture(){
try {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(rectangle);
File file=createTempFilePath();
ImageIO.write(screenShot, "jpg", file);
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private File createTempFilePath() throws IOException {
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmssS");
return File.createTempFile("screen-"+LocalDateTime.now().format(formatter),".jpg");
}
}
After run this program, I was expecting a image with my entire screen (MacOS menu, Intellij, etc):
Instead I got a image only containing my desktop's background:
I think robot is trying to take a screenshot only of my program. What should I do to take a screenshot of the opened screens?
The problem was MacOS permission. According with this answer, the program needs permission to record the screen. I simply added the access to IntelliJ in System Preferences -> Security and Privacy -> Privacy -> Screen Recording and it worked.