12

I am trying to capture screen shots in my JavaFX application using Robot class,

this is the code which 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 is working perfectly in windows operating system, but showing an error of headless environment in MAC OS at Robot robot = new Robot();

4
  • Can you post the error or exception
    – GingerHead
    Nov 21, 2012 at 5:42
  • java.awt.AWTException: headless environment at Robot robot = new Robot(); Nov 21, 2012 at 6:00
  • What Java Version is the Mac running?
    – jewelsea
    Nov 21, 2012 at 8:10
  • java version "1.6.0_37" Java(TM) SE Runtime Environment (build 1.6.0_37-b06-434-11M3909) Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01-434, mixed mode) Nov 24, 2012 at 5:32

3 Answers 3

32

This is to answer my own question, after searching many resources.

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

static {

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

Thanks.

1
  • did this work in headless environment ? Dec 16, 2021 at 12:51
3

From their API I can see the following:

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

So you need to check your hardware and their drivers.

2

You can simply add this line of code System.setProperty("java.awt.headless", "false"); before the Robot robot = new Robot();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.