Setting java.awt.headless=true programmatically

reto picture reto · Mar 31, 2010 · Viewed 60.5k times · Source

I'm trying to set java.awt.headless=true during the application startup but it appears like I'm too late and the non-headless mode has already started:

static {
    System.setProperty("java.awt.headless", "true");
    /* java.awt.GraphicsEnvironment.isHeadless() returns false */
}

Is there another way set headless to true beside -Djava.awt.headless=true? I would prefer not configure anything on the console.

Answer

reto picture reto · Mar 31, 2010

I was working with a main() in a class which statically loads different parts of JFreeChart in Constants (and other static code).

Moving the static loading block to the top of the class solved my problem.

This doesn't work:

  public class Foo() {
    private static final Color COLOR_BACKGROUND = Color.WHITE;

    static { /* too late ! */
      System.setProperty("java.awt.headless", "true");
      System.out.println(java.awt.GraphicsEnvironment.isHeadless());
      /* ---> prints false */
    }

    public static void main() {}
  }

Have java execute the static block as early as possible by moving it to the top of the class!

  public class Foo() {
    static { /* works fine! ! */
      System.setProperty("java.awt.headless", "true");
      System.out.println(java.awt.GraphicsEnvironment.isHeadless());
      /* ---> prints true */
    }

    private static final Color COLOR_BACKGROUND = Color.WHITE;

    public static void main() {}
  }

When thinking about it this makes perfectly sense :). Juhu!