Headless environment error in java.awt.Robot class with MAC OS

I am trying to capture screenshots in my JavaFX application using the Robot class,

this is the code i used in my application:

 Rectangle screenBounds = new Rectangle(Screen.getPrimary().getBounds().getWidth(), Screen.getPrimary().getBounds().getHeight()); Robot robot = new Robot(); BufferedImage img = robot.createScreenCapture(new java.awt.Rectangle( (int) screenBounds.getX(), (int) screenBounds.getY(), (int) screenBounds.getWidth(), (int) screenBounds.getHeight())); 

It works fine on Windows, but shows a headless environment error on MAC OS in Robot robot = new Robot();

+7
source share
2 answers

This is the answer to my question after searching many resources.

I used the following code to disable the headless environment, and the problem is resolved.

 static { System.setProperty("java.awt.headless", "false"); } 

Thanks.

+10
source

From my API, I see the following:

  • Applet constructors and all heavyweight components (*) modified to throw a HeadlessException if the display, keyboard, and mouse are not supported by the implementation of the toolkit
  • The Robot constructor throws an AWTException if the display, keyboard, and mouse are not supported by the implementation of the toolkit.
  • Many of the methods in Toolkit and GraphicsEnvironment, with the exception of fonts, images, and printing, are modified by HeadlessException if the display, keyboard, and mouse are not supported
  • Other methods that may be affected by the lack of a display, keyboard, or mouse are changed to throw a HeadlessException.
  • It is worth noting that a HeadlessException is thrown if and only if isHeadless returns true, and that all javadoc comments should indicate this

So, you need to check your hardware and their drivers.

+2
source

All Articles